這段代碼可以讓你做你想做的事,但它沒有利用更新的語言功能,也不便攜。
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再現了它。 –