我如何在Delphi控制台应用程序中实现IsKeyPressed函数? [英] How i can implement a IsKeyPressed function in a delphi console application?
问题描述
我有一个delphi控制台应用程序,当用户按任何键时,我需要终止,问题是我不知道如何实现一个功能来检测一个按键的时间,我想做这样的事情。 / p>
I have a delphi console application which i need terminate when the user press any key, the problem is which i don't know how implement a function to detect when a key is pressed , i want to do something like so.
{$APPTYPE CONSOLE}
begin
MyTask:=MyTask.Create;
try
MyTask.RunIt;
while MyTask.Running and not IsKeyPressed do //how i can implement a IsKeyPressed function?
MyTask.SendSignal($56100AA);
finally
MyTask.Stop;
MyTask.Free;
end;
end。
推荐答案
您可以编写一个功能来检测是否按下了一个键,检查 控制台输入缓冲区
。
You can write a function to detect if a key was pressed checking the console input buffer
.
每个控制台都有一个输入缓冲区
包含输入事件
记录的队列。当控制台的窗口有
键盘焦点时,控制台将
每个输入事件(例如单个
按键,鼠标移动或
a鼠标按钮点击)作为输入
记录,它放在控制台的
输入缓冲区中。
Each console has an input buffer that contains a queue of input event records. When a console's window has the keyboard focus, a console formats each input event (such as a single keystroke, a movement of the mouse, or a mouse-button click) as an input record that it places in the console's input buffer.
首先你必须调用<一个href =http://msdn.microsoft.com/en-us/library/ms683207%28v=vs.85%29.aspx> GetNumberOfConsoleInputEvents 函数来获取事件数,然后检索事件使用 PeekConsoleInput 功能,并检查事件是否为 KEY_EVENT
最后使用 FlushConsoleInputBuffer 。
First you must call the GetNumberOfConsoleInputEvents function to get the number of events, then retrieve the event using the PeekConsoleInput function and check if the event is a KEY_EVENT
finally flush the console input buffer using FlushConsoleInputBuffer.
查看此示例
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;
这篇关于我如何在Delphi控制台应用程序中实现IsKeyPressed函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!