C语言 SetWindowsHookEx -VK_LSHIFT和“搜索”键盘按钮之间的差异

tv6aics1  于 2023-05-28  发布在  Windows
关注(0)|答案(1)|浏览(161)

我使用SetWindowsHookEx捕获键盘事件

SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0)

HookCallback

LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        // the action is valid: HC_ACTION.
        if (wParam == WM_KEYDOWN)
        {
            kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
            printf("%ld\n", kbdStruct.vkCode);
        }
    }
}

按下“左移”时输出为

160

当按下“搜索”按钮(笔记本上带有放大镜图标的按钮)时,输出为

160
91
132

如何检查HookCallback中是否按下了“左移”或“搜索”按钮?

yb3bgrhw

yb3bgrhw1#

160是VK_LSHIFT,91是VK_LWIN,132是VK_F21。参见Virtual-Key Codes。唯一标准化的搜索键是VK_BROWSER_SEARCH,因此很明显,您的键盘制造商正在使用非标准键作为其搜索键。
您需要根据需要记住从一个事件到下一个事件所看到的键,例如:

bool LeftShiftIsDown = false;
bool LeftWinIsDown = false;
bool F21IsDown = false;
bool SearchIsDown = false;

LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT *kbdStruct = (KBDLLHOOKSTRUCT*) lParam;
        if (wParam == WM_KEYDOWN)
        {
            printf("%ld is down\n", kbdStruct->vkCode);
            switch (kbdStruct->vkCode)
            {
                case VK_LSHIFT:
                    LeftShiftIsDown = true;
                    break;
            case VK_LWIN:
                    LeftWinIsDown = true;
                    break;
            case VK_F21:
                    F21IsDown = true;
                    break;
            }

            if (LeftShiftIsDown && LeftWinIsDown && F21IsDown)
            {
                if (!SearchIsDown)
                {
                    SearchIsDown = true;
                    printf("Search is down\n");
                }
            }
        }
        else if (wParam == WM_KEYUP)
        {
            printf("%ld is up\n", kbdStruct->vkCode);
            switch (kbdStruct->vkCode)
            {
                case VK_LSHIFT:
                    LeftShiftIsDown = false;
                    break;
                case VK_LWIN:
                    LeftWinIsDown = false;
                    break;
                case VK_F21:
                    F21IsDown = false;
                    break;
            }

            if (!(LeftShiftIsDown && LeftWinIsDown && F21IsDown))
            {
                if (SearchIsDown)
                {
                    SearchIsDown = false;
                    printf("Search is up\n");
                }
            }
        }
    }
    return CallNextHookEx(0, nCode, wParam, lParam);
}

相关问题