有时候,我们需要在 console 中检查是否有按键按下,对于c语言来说,有 kbhit 和 keypressed, 但是Delphi库中没有对应的现成函数。
经过搜索,最终找到了一段代码【参考1】,根据这段代码,编写下面的测试程序:
program Project5; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils,Windows; function KeyPressed:Boolean; var lpNumberOfEvents : DWORD; lpBuffer : TInputRecord; lpNumberOfEventsRead : DWORD; nStdHandle : THandle; begin Result:=false; //get the console handle nStdHandle := GetStdHandle(STD_INPUT_HANDLE); lpNumberOfEvents:=0; //get the number of events GetNumberOfConsoleInputEvents(nStdHandle,lpNumberOfEvents); if lpNumberOfEvents<> 0 then begin //retrieve the event PeekConsoleInput(nStdHandle,lpBuffer,1,lpNumberOfEventsRead); if lpNumberOfEventsRead <> 0 then begin if lpBuffer.EventType = KEY_EVENT then //is a Keyboard event? begin if lpBuffer.Event.KeyEvent.bKeyDown then //the key was pressed? Result:=true else FlushConsoleInputBuffer(nStdHandle); //flush the buffer end else FlushConsoleInputBuffer(nStdHandle);//flush the buffer end; end; end; var i:integer; begin while (keypressed()=false) do begin write('waiting '); writeln(i); sleep(1000); inc(i); end; end.
运行结果:
参考:
1.https://stackoverflow.com/questions/5845080/how-i-can-implement-a-iskeypressed-function-in-a-delphi-console-application