gpt4 book ai didi

c++ - 以编程方式检测按键的更好方法?

转载 作者:可可西里 更新时间:2023-11-01 11:12:24 24 4
gpt4 key购买 nike

我目前正在使用这个:

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;
}

关于c++ - 以编程方式检测按键的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com