键盘输入Win32 消息循环

2021-12-17 00:00:00 winapi c++

如何处理 Windows 消息循环中的按键和按键事件?我需要能够调用两个函数 OnKeyUp(char c);OnKeyDown(char c);.

How do I handle key presses and key up events in the windows message loop? I need to be able to call two functions OnKeyUp(char c); and OnKeyDown(char c);.

我从谷歌搜索中发现的当前文献让我对 WM_CHAR 或 WM_KEYUP 和 WM_KEYDOWN 感到困惑,并且通常针对 PDA 或托管代码,而我使用的是 C++.

Current literature I've found from googling has lead me to confusion over WM_CHAR or WM_KEYUP and WM_KEYDOWN, and is normally targeted at PDA or Managed code, whereas I'm using C++.

推荐答案

使用char c = MapVirtualKey(param,MAPVK_VK_TO_CHAR);将虚拟键码转换为char,并处理WM_KEYUP和WM_KEYDOWN及其wParams.

Use char c = MapVirtualKey(param,MAPVK_VK_TO_CHAR); to convert virtual key codes to char, and process WM_KEYUP and WM_KEYDOWN and their wParams.

if (PeekMessage (&mssg, hwnd, 0, 0, PM_REMOVE))
{
    switch (mssg.message)
    {
        case WM_QUIT:
            PostQuitMessage (0);
            notdone = false;
            quit = true;
            break;

        case WM_KEYDOWN:
            WPARAM param = mssg.wParam;
            char c = MapVirtualKey (param, MAPVK_VK_TO_CHAR);
            this->p->Input ()->Keyboard ()->Listeners ()->OnKeyDown (c);
            break;

        case WM_KEYUP:
            WPARAM param = mssg.wParam;
            char c = MapVirtualKey (param, MAPVK_VK_TO_CHAR);
            this->p->Input ()->Keyboard ()->Listeners ()->OnKeyUp (c);
            break;
    }
    // dispatch the message
    TranslateMessage (&mssg);
    DispatchMessage (&mssg);
}

相关文章