I\'m trying to do something which I think should be simple: do a blocking read from standard input, but timing out after a specified interval if no data is available.
<
Using GetStdHandle + WaitForSingleObject works fine. But be sure to set the approriate flags and flush the console buffer as well before entering the loop.
In short (without error checks)
std::string inStr;
DWORD fdwMode, fdwOldMode;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hStdIn, &fdwOldMode);
// disable mouse and window input
fdwMode = fdwOldMode ^ ENABLE_MOUSE_INPUT ^ ENABLE_WINDOW_INPUT;
SetConsoleMode(hStdIn, fdwMode);
// flush to remove existing events
FlushConsoleInputBuffer(hStdIn);
while (!abort)
{
if (WaitForSingleObject(hStdIn, 100) == WAIT_OBJECT_0)
{
std::getline(std::cin, inStr);
}
}
// restore console mode when exit
SetConsoleMode(hStdIn, fdwOldMode);