I want to detect whether or not there is input waiting on stdin in Windows.
I use the following generic structure on Linux:
fd_set currentSocketSet;
As already pointed out, in Windows you have to use GetStdHandle() and the returned handle cannot be mixed with sockets. But luckily, the returned handle can be tested with WaitForSingleObject(), just like many other handles in Windows. Therefere, you could do something like this:
#include
#include
BOOL key_was_pressed(void)
{
return (WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),0)==WAIT_OBJECT_0);
}
void wait_for_key_press(void)
{
WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),INFINITE);
}
int main()
{
if(key_was_pressed())
printf("Someone pressed a key beforehand\n");
printf("Wait until a key is pressed\n");
wait_for_key_press();
if(key_was_pressed())
printf("Someone pressed a key\n");
else
printf("That can't be happening to me\n");
return 0;
}
EDIT: Forgot to say that you need to read the characters from the handle in order to key_was_pressed() to return FALSE.