
{$UNDEF Crt} {$UNDEF NoCrt}
{$DEFINE NoCrt - one of Crt, NoCrt}
{$IFDEF Crt}{$IFDEF NoCrt} FAIL ; {$ENDIF}{$ENDIF}

program KeyBuffer ;

uses {$IFDEF Crt} Crt {for ReadKey}, {$ENDIF} Dos {for Registers} ;


function KeyBuff(var X : word) : boolean ;
var R : Registers ;
begin with R do begin
    AH := $01 ; Intr($16, R) ;
    if (Flags and FZero)<>0 then KeyBuff := false
      else begin X := AX ; KeyBuff := true end ;
    end end {KeyBuff} ;

function Keyed(var CC : boolean ; var C : char) : boolean ;
var BV : boolean ; Z : word ;
begin BV := KeyBuff(Z) ; Keyed := BV ;
  if BV then begin CC := Lo(Z)=0 ;
    if CC then C := char(Hi(Z)) else C := char(Lo(Z)) ;
    end ;
  end {Keyed} ;

{$IFDEF NoCrt}
function ReadKey : char { in lieu of Crt.ReadKey } ;
const Buff : char = #0 ;
var R : registers ;
begin
  if Buff<>#0 then begin ReadKey := Buff ; Buff := #0 end else
    with R do begin AH := 0 ; Intr($16, R) ;
    if AL=0 then Buff := char(AH) ;
    ReadKey := char(AL) end ;
  end {ReadKey} ;
{$ENDIF}

procedure Wait(T : byte) { instead of Crt.Delay ; unit = 1/18 sec } ;
var XT : byte ; P : ^byte ;
begin P := Ptr(Seg0040, $6C) ;
  repeat
    if XT<>P^ then begin XT := P^ ; Dec(T) end ;
    until T=0 ;
  end {Wait} ;


var B, BB : boolean ; Y : word ; Ch : char ; const Esc = #27 ;

BEGIN ;
repeat
  Write('KeyBuff (esc) ?') ; Wait(12) ; B := KeyBuff(Y) ;
  Write(' Ready:', B:6) ;
  if B then begin
    Write(' Scan:',
      Y:6, Hi(Y):5, ':', Lo(Y):3, char(Lo(Y)):2, 'ReadKey:':12) ;
    Ch := ReadKey ; Write(Ord(Ch):4, Ch:2) ;
    if Ch=#0 then begin Ch := ReadKey ; Write(Ord(Ch):4, Ch:2) end ;
    end ;
  Writeln until Ch=Esc ;
Write('<cr>?') ; Readln ;
Ch := #0 ;
repeat
  Write('Keyed? (esc) ') ; Wait(12) ; B := Keyed(BB, Ch) ;
  Write(' Ready:', B:6) ;
  if B then begin Write('  Func:', BB:6, Ord(Ch):5, Ch:2, 'ReadKey:':12) ;
    Ch := ReadKey ; Write(Ord(Ch):4, Ch:2) ;
    if Ch=#0 then begin Ch := ReadKey ; Write(Ord(Ch):4, Ch:2) end ;
    end ;
  Writeln until Ch=Esc ;
Write('<cr>?') ; Readln ;
END.

www.merlyn.demon.co.uk  1998/02/09 ff.

KeyBuff pre-reads the first key in the input buffer, if any.
KeyBuff could use asm...


Derived from a post by Joe Merten <joe@jme.de>, JME Engineering Berlin :
If your reason to replace the KeyPressed-Function is only
that you don't want to use the CRT-unit, try:
  Function KeyPressed: Boolean; Assembler;
  Asm  Mov AH,$01 ; Int $16
    Mov AL,TRUE ; JNZ @Ende ; Mov AL,FALSE ; @Ende: end;
But if you want to prevent the BIOS-call, try:
    Function KeyPressed: Boolean;
    begin KeyPressed := MemW[Seg0040:$1A]<>MemW[Seg0040:$1C] end ;
which simply checks the emptyness of the keyboard-buffer.
 
