This code will allow you to do what you want, but it does not take advantage of newer language features, nor is it portable.
events[0] = CreateEvent(NULL,FALSE,FALSE,NULL); // Obtain a Windows handle to use with a timer
events[1] = GetStdHandle(STD_INPUT_HANDLE); // Get a Windows handle to the keyboard input
// Create a timer object that will strobe an event every ten seconds
DemoTimer = timeSetEvent(10000,0,(LPTIMECALLBACK)events[0],NULL,TIME_PERIODIC|TIME_CALLBACK_EVENT_SET);
while (done == false)
{
// Wait for either the timer to expire or a key press event
dwResult = WaitForMultipleObjects(2,events,false,INFINITE);
if (dwResult == WAIT_FAILED)
{
dwResult = GetLastError();
done = true;
}
else
{
if (dwResult == WAIT_OBJECT_0) // WAIT_OBJECT_0 corresponds to the timer event
{
DoTimeoutEvent();
}
else
{
// Any other event will be a keypress
if (_kbhit() != 0) // Verify that a key was pressed so that we do not block when we query for a value
{
int val = _getch();
// At this point, we process the key value
}
}
}
}
You are not going to be able to break out of getch(). The best bet is to check for data in the STDIN buffer and only make the call after you have something to read. This example uses kbhit(), but instead of using a polling loop where it periodically checks for buffer activity, it hooks the underlying handle to the input stream and waits for activity.
Using a second thread as a one-shot timer is also not the most efficient way to go. The timer in this code uses a Microsoft specific object. It is coded to fire off every ten seconds, but you can certainly change that.