这段代码可以让你做你想做的事,但它没有利用更新的语言功能,也不便携。
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
}
}
}
}
你不能打出getch()
。最好的选择是检查STDIN缓冲区中的数据,并在有需要阅读的地方进行调用。本示例使用kbhit()
,但它不是使用定期检查缓冲区活动的轮询循环,而是将底层句柄挂接到输入流并等待活动。
使用第二个线程作为一次性定时器也不是最有效的方法。此代码中的计时器使用Microsoft特定的对象。它被编码为每十秒钟发射一次,但你当然可以改变它。
不,这是一个来自黑暗时代的陈旧功能,不应再使用!你应该在'STDIN'上做'epoll'。 –
我正在使用getch();检索密钥的ascii值。那些做同样的事情吗? – user7327796
是的,有很多方法可以轮询_standard input_(或任何其他文件描述符)以进行活动并处理其中收到的数据。 'getch()'就是其中之一,但它有极大的局限性,正如你发现的那样。这甚至不是标准的;它是一个DOS函数,并且(我认为)ncurses再现了它。 –