我以前做过几次类似的事情:
首先声明几个全局变量:
var
hIn: THandle;
hTimer: THandle;
threadID: cardinal;
TimeoutAt: TDateTime;
WaitingForReturn: boolean = false;
TimerThreadTerminated: boolean = false;
二、添加功能
function TimerThread(Parameter: pointer): integer;
var
IR: TInputRecord;
amt: cardinal;
begin
result := 0;
IR.EventType := KEY_EVENT;
IR.Event.KeyEvent.bKeyDown := true;
IR.Event.KeyEvent.wVirtualKeyCode := VK_RETURN;
while not TimerThreadTerminated do
begin
if WaitingForReturn and (Now >= TimeoutAt) then
WriteConsoleInput(hIn, IR, 1, amt);
sleep(500);
end;
end;
procedure StartTimerThread;
begin
hTimer := BeginThread(nil, 0, TimerThread, nil, 0, threadID);
end;
procedure EndTimerThread;
begin
TimerThreadTerminated := true;
WaitForSingleObject(hTimer, 1000);
CloseHandle(hTimer);
end;
procedure TimeoutWait(const Time: cardinal);
var
IR: TInputRecord;
nEvents: cardinal;
begin
TimeOutAt := IncSecond(Now, Time);
WaitingForReturn := true;
while ReadConsoleInput(hIn, IR, 1, nEvents) do
if (IR.EventType = KEY_EVENT) and
(TKeyEventRecord(IR.Event).wVirtualKeyCode = VK_RETURN)
and (TKeyEventRecord(IR.Event).bKeyDown) then
begin
WaitingForReturn := false;
break;
end;
end;
现在您可以使用TimeoutWait
等待返回,但不超过给定的秒数。但是您必须在使用此功能之前进行设置hIn
和调用:StartTimerThread
begin
hIn := GetStdHandle(STD_INPUT_HANDLE);
StartTimerThread;
Writeln('A');
TimeoutWait(5);
Writeln('B');
TimeoutWait(5);
Writeln('C');
TimeoutWait(5);
EndTimerThread;
end.
您可以摆脱StartTimerThread
,特别是如果您每次调用启动一个线程,但TimeoutWait
连续多次调用可能会更加棘手。