Pascal readkey 命令问题

Pascal readkey command issue

我使用了两次 readkey 命令。 它第一次工作正常,但拒绝在第二次工作。 我希望该程序等待我的按键,但程序自行结束。

代码:

program window1;

uses crt;

var x,y:integer;

begin

clrscr;
window(1,1,80,25);
readkey;

//writting just window borders
for x:=1 to 80 do
 for y:=1 to 25 do
 begin
   if (x >= 2) and (x <= 79) and
      (y >= 2) and (y <= 24) then
     continue
   else
     begin
       gotoxy(x,y);
       write('*');
     end;
 end;

gotoxy(2,23);
write('inside window press any key to exit...');
readkey;
//readln;

end.

我按了向上箭头键。

I've pressed the up arrow key

键盘上的某些键会生成所谓的扩展键。箭头键(以及其他键)就是这样的键。他们 return 两个字符,而不是一个。第一个字符是ASCII 0,第二个是按键的扫描码。

对于ReadKeydocumented:

ReadKey reads 1 key from the keyboard buffer, and returns this. If an extended or function key has been pressed, then the zero ASCII code is returned. You can then read the scan code of the key with a second ReadKey call.

我可以补充一点,如果键盘缓冲区为空(但仅当它为空时),ReadKey 等待输入。

因此,当您的程序第一次调用 ReadKey 并且您按下“向上箭头键”时,两个字节被放入缓冲区,$00 和 $48。第一个 ($00) 被 return 编辑到您的代码中,向上箭头的扫描代码保留在输入缓冲区中。当您稍后再次调用 ReadKey 时,它会从缓冲区接收扫描代码并立即继续,而不会停止输入。

您可以通过以下两种方式之一处理此问题:

1.Write 一个处理扩展键的过程,比如 WaitForAnyKey

procedure WaitForAnyKey;
var
  c: char;
begin
  c:=ReadKey;
  if c=#0 then
    c:=ReadKey;
end;

你调用它而不是直接调用 ReadKey

2.Write 等待并仅接受特定密钥的过程:

procedure WaitForCR; // wait for CR, Carriage Return (Enter)
const
  CR=#13;
var
  c: Char;
begin
  repeat
    c:=ReadKey;
  until c=CR;
end

你调用它而不是直接调用 ReadKey