The following code captures any key press. It is used to return from a function.
Documentation:
https://learn.microsoft.com/en-us/windows/console/readconsoleinput?redirectedfrom=MSDN
https://learn.microsoft.com/en-us/windows/console/input-record-str?redirectedfrom=MSDN
https://learn.microsoft.com/en-us/windows/console/key-event-record-str?redirectedfrom=MSDN
Purpose
The function does some calculations, the progress of which are shown to the user on the console. When all is done the user wishes to return from the function. She does that by pressing any key. In all my other applications the user can return with the Esc key, so it is nice to have that work also here.
It works by allocating the console and setting handles for output from and input to the console. Flags OKflg_out and OKflg_in are set to verify the operations at the end. The for (; ;)-loop after the message "Press any key." to the user ends when the user presses a key.
The numerical code for the pressed key is (((irec.Event).KeyEvent).uChar).AsciiChar, but it is not used here. It could of course be used as a return code to determine the following actions in the calling function.
#include <windows.h>
// Various other includes.
void wrintf0(HANDLE stdOut, unsigned char *message)
{
DWORD written=0;
WriteConsoleA(stdOut, message, strleni(message), &written, NULL);
}
#define wrintf(message) wrintf0(stdOut,message)
// Various code lines.
void Myfunction(void)
{
unsigned char OKflg_in=0,OKflg_out=0;
HANDLE stdIn,stdOut;
// Various code lines.
AllocConsole();
stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (stdOut != NULL && stdOut != INVALID_HANDLE_VALUE)
{
OKflg_out = 1;
stdIn = GetStdHandle(STD_INPUT_HANDLE);
if (stdIn != NULL && stdIn != INVALID_HANDLE_VALUE) OKflg_in = 1;
}
// Various code lines.
if (OKflg_out)
{
if (OKflg_in)
{
DWORD cc;
INPUT_RECORD irec;
wrintf("Press any key.");
for(; ;) {
ReadConsoleInput(stdIn, &irec, 1, &cc );
if (irec.EventType == KEY_EVENT && ((irec.Event).KeyEvent).bKeyDown) break;
}
CloseHandle(stdIn);
}
CloseHandle(stdOut);
}
FreeConsole();
return;
}