如何修复“被忽略的按键”

时间:2019-08-21 04:28:53

标签: c++ windows winapi visual-c++ keyevent

我的问题是,在添加了捕获键之后,我的代码开始无法正常工作。

更详细:在按下某个组合键(在我的情况下为CTRL + q和CTRL + e)后,程序的任务是模拟某些程序中的击键。如果您使用程序中的按钮,则一切正常,但是在添加捕获后,箭头停止了工作(Enter和Esc起作用,我没有检查其余的键)。

在某些程序中,我需要此功能来进行快速同步,在这种情况下,您必须多次按键盘上的箭头。

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
    DWORD CTRL_key = 0;

    if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)))
    {
        KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam);
        DWORD dwMsg = 1;
        dwMsg += hooked_key.scanCode << 16;
        dwMsg += hooked_key.flags << 24;
        char lpszKeyName[1024] = { 0 };

        int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1;

        int key = hooked_key.vkCode;

        CTRL_key = GetAsyncKeyState(VK_CONTROL);

        if (key >= 'A' && key <= 'Z')
        {

            if (CTRL_key != 0 && key == 'q')
            {
                //MessageBox(NULL, "Pressed", "H O T K E Y", MB_OK);
                CTRL_key = 0;
                //
                Sleep(1000);
                keybd_event(VK_RETURN, 0x9C, 0, 0);
                Sleep(50);
                keybd_event(VK_RETURN, 0x9C, KEYEVENTF_KEYUP, 0);
                Sleep(100);
                for (int i = 0; i < 6; i++) {
                    keybd_event(VK_UP, 0x26, 0, 0);
                    Sleep(50);
                    keybd_event(VK_UP, 0x26, KEYEVENTF_KEYUP, 0);
                    Sleep(50);
                }
                for (int i = 0; i < 5; i++) {
                    keybd_event(VK_RIGHT, 0x27, 0, 0);
                    Sleep(50);
                    keybd_event(VK_RIGHT, 0x27, KEYEVENTF_KEYUP, 0);
                    Sleep(50);
                }
                keybd_event(VK_DOWN, 0x28, 0, 0);
                Sleep(50);
                keybd_event(VK_DOWN, 0x28, KEYEVENTF_KEYUP, 0);
                keybd_event(VK_RETURN, 0x9C, 0, 0);
                Sleep(50);
                keybd_event(VK_RETURN, 0x9C, KEYEVENTF_KEYUP, 0);
                Sleep(50);
                Sleep(6000);
                keybd_event(VK_ESCAPE, 0x1B, 0, 0);
                Sleep(500);
                keybd_event(VK_ESCAPE, 0x1B, KEYEVENTF_KEYUP, 0);
                Sleep(1000);
            }

            if (CTRL_key != 0 && key == 'e')
            {
                MessageBox(NULL, "Shutting down", "H O T K E Y", MB_OK);
                PostQuitMessage(0);
            }

            CTRL_key = 0;
        }

    }
    return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

如果要查看整个代码,请单击here! 预先谢谢你!

1 个答案:

答案 0 :(得分:0)

解决方案很简单。在函数中,单击箭头时,需要另一个参数。

                    keybd_event(VK_UP, 0x26, KEYEVENTF_EXTENDEDKEY, 0);
                    Sleep(50);
                    keybd_event(VK_UP, 0x26, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);