2011-04-30 4 views
7

나는 어떤 키를 누를 때 종료해야하는 델파이 콘솔 응용 프로그램을 가지고 있는데, 문제는 키를 눌렀을 때 감지하는 기능을 구현하는 방법을 모르는 것과 같다.어떻게 델파이 콘솔 응용 프로그램에서 IsKeyPressed 함수를 구현할 수 있습니까?

{$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.

+1

당신이 바쁜 루프를 하시겠습니까? 왜 Ctrl + Break를 중단하지 않습니까? –

답변

9

console input buffer을 검사하는 키가 눌러 졌는지 감지하는 기능을 작성할 수 있습니다.

각 콘솔 입력 이벤트 기록 큐를 포함하는 입력 버퍼를 갖는다. 콘솔의 창에 키보드 포커스가있는 경우 콘솔에서 입력 각 입력 이벤트 ( 키 스트로크, 마우스의 움직임 또는 마우스 단추 클릭 )를 입력 레코드로 콘솔의 형식으로 입력합니다 입력 버퍼.

먼저 당신은 다음 PeekConsoleInput 기능을 사용하여 이벤트를 검색하고 이벤트가 KEY_EVENT 마침내 FlushConsoleInputBuffer을 사용하여 콘솔 입력 버퍼를 플러시 있는지 확인, 이벤트의 수를 얻기 위해 GetNumberOfConsoleInputEvents 함수를 호출해야합니다.

확인이 샘플

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; 
관련 문제