我目前正在使用此:
while (1)
{
if (GetAsyncKeyState(VK_F1))
{
//do something
}
}
检测用户是否按下某个键,在这种情况下为F1.我发现这会大量消耗CPU使用率,我的问题是,是否有更好的方法来检测按键?
解决方法:
更好的方法是使用WndProc().因此,请使用标准的WM_KEYDOWN / WM_KEYUP消息来处理键盘输入.这是一个例子:
LRESULT CALLBACK WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch ( uMsg )
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
if ( wParam == VK_F1 )
{
// Do something here
return 0L;
}
break;
}
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
//Step 1: Registering the Window Class
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
// lots of other attrs ...
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
return 0;
// Step 2: Creating the Window
hwnd = CreateWindowEx(
...
g_szClassName,
...);
if(hwnd == NULL)
return 0;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 3: The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}