Search code examples
winapikeyboard-hook

Disabling keys using windows hooks


I am trying to completely disable the letter 'a' on the keyboard using lowlevel keyboard hook. The problem is that when i return 0 from keyboardproc the key is not disabled but when i return 1 it gets disabled. I thought that returning from keyboardproc without calling CallNextHookEx blocks the message. Is there any difference between returning 0 and returning 1.

LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT* details = (KBDLLHOOKSTRUCT*) lParam;

    if(code == HC_ACTION && wParam == WM_KEYDOWN)
    {
        if(details->vkCode == 0x41)
        {
            return 1;
        }
    }

    return CallNextHookEx(g_hhkKeyboard, code, wParam, lParam);     
}

Solution

  • From the LowLevelKeyboardProc MSDN documentation:

    If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.

    [emphasis mine]

    So it's not entirely well documented, what happens if you actually return 0. I'd guess this value causes the system to call the next hook procedure in the chain anyway, and it eventually gets processed by your default window procedure.

    I have recently written a simple app that requires you to hold Caps Lock for a given amount of time in order to toggle it, and whenever I actually handle this key in my LowLevelKeyboardProc, I always return 1, otherwise

    CallNextHookEx( NULL, nCode, wParam, lParam );
    

    Additional note: If you're targetting NT/XP/2003 and newer systems, you can pass NULL in the first CallNextHookEx parameter, since it's ignored.