In a console application, what code should appear after
WriteLn('Hit any key to continue...');
to wait until any key is pressed?
Target platform: Windows
One of the most important Win32 functions is WaitForSingleObject. Indeed, you almost always rely on this function and/or its relatives when you write anything but a very simple single-threaded application.
Typically, you wait on events, mutexes, processes etc., but you can also wait on console input:
program Project4;
{$APPTYPE CONSOLE}
uses
Windows, SysUtils;
begin
Writeln('Press any key to continue.');
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), INFINITE);
Writeln('Thank you for pressing that key.');
Sleep(1000);
end.
Please note that this really waits for any console input, not only keyboard events. It also responds to mouse events, window resizing events, etc.
So, you may want to investigate the kind of event using the ReadConsoleInput function.
I'd try something like this:
begin
Writeln('Press any key to continue.');
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
var ci := Default(TInputRecord);
var n: Cardinal;
while ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), ci, 1, n) and (ci.EventType <> KEY_EVENT) do;
Writeln('Thank you for pressing that key.');
Sleep(1000);
end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With