我的程式正在等待F4按下熱鍵以退出。
我打電話Sleep(1)是因為沒有這個,我使用了 18% 的 CPU。這是正確的方法嗎?我的直覺告訴我有更好的方法。
我知道鍵盤輸入是基于中斷的,但是有沒有辦法讓執行緒休眠,直到鍵盤狀態更改被注冊?
#include <Windows.h>
#include <iostream>
#include <thread>
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
while (!(GetAsyncKeyState(VK_F4) >> 15)) {
Sleep(1); // Sleep for 1 ms to avoid wasting CPU
}
return 0;
}
uj5u.com熱心網友回復:
查看RegisterHotKey、UnRegisterHotkey、GetMessage、TranslateMessage和DispatchMessage 之類的
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
RegisterHotKey(0, 1, MOD_NOREPEAT, VK_F4);
MSG msg;
while (GetMessage(&msg, 0, 0, 0) != 0) // TODO: error handling
{
if (msg.message == WM_HOTKEY)
{
if (msg.wParam == 1) {
break;
}
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnregisterHotKey(0, 1);
return 0;
}
GetMessage()將阻塞,直到它接收到一個視窗訊息,該訊息將其喚醒。獲取Process Explorer的副本,查看行程詳細資訊并查看它在等待時不使用單個 CPU 周期。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450490.html
上一篇:Crash Course Computer Science - 1.計算機早期歷史-Early Computing
