Global keyboard hook with WH_KEYBOARD_LL and keybd_event (windows)

前端 未结 3 1250
无人共我
无人共我 2020-12-30 09:38

I am trying to write a simple global keyboard hook program to redirect some keys. For example, when the program is executed, I press \'a\' on the keyboard, the program can d

3条回答
  •  粉色の甜心
    2020-12-30 09:54

    Your callback function execute twice because of WM_KEYDOWN and WM_KEYUP. When you down a key of your keyboard, windows calls the callback function with WM_KEYDOWN message and when you release the key, windows calls the callback function with WM_KEYUP message. That's why your callback function execute twice.

    You should change your switch statement to this:

    switch (wParam)
    {
        case WM_KEYDOWN:
        case WM_SYSKEYDOWN:
        case WM_KEYUP:
        case WM_SYSKEYUP:
            PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
            if (fEatKeystroke = (p->vkCode == 0x41))  //redirect a to b
            {     
                printf("Hello a\n");
    
                if ( (wParam == WM_KEYDOWN) || (wParam == WM_SYSKEYDOWN) ) // Keydown
                {
                    keybd_event('B', 0, 0, 0);
                }
                else if ( (wParam == WM_KEYUP) || (wParam == WM_SYSKEYUP) ) // Keyup
                {
                    keybd_event('B', 0, KEYEVENTF_KEYUP, 0);
                }
                break;
            }
            break;
    }
    

    About your second question, I think you have already got from @Ivan Danilov answer.

提交回复
热议问题