Salvador
Salvador

Reputation: 16492

How i can implement a IsKeyPressed function in a delphi console application?

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.

Upvotes: 8

Views: 4342

Answers (1)

RRUZ
RRUZ

Reputation: 136451

You can write a function to detect if a key was pressed checking the console input buffer.

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.

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.

Check this sample

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;

Upvotes: 13

Related Questions