0

I have written the following method that prevents all keys from being pressed:

private IntPtr HookHandler(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam)
{
    if (nCode >= 0)
    {
        ...

        //Return a nonzero value to prevent the system from passing the message to the
        //rest of the hook chain or the target window procedure.
        return (IntPtr)1;
    }

    return NativeMethods.CallNextHookEx(_hookID, nCode, wParam, ref lParam);
}

When the above code runs, though, it allows keys like my keyboard's calc key or the email key, etc.

I debug, and the code does get to the return (IntPtr)1; line (and it does show correctly what key is being pressed), but by then, the calc window (or other) has already opened. Even if I return a 1, its too late.

Is there something I can be doing different here?

Gabriel McAdams
  • 56,921
  • 12
  • 61
  • 77

1 Answers1

2

Well, that ought to work. Normal routing is from a WM_KEYDOWN message to a WM_APPCOMMAND message generated by the default window procedure. WM_XBUTTONUP is another route but an unlikely one. Have a look with Spy++ to see if anything unusual is happening.

You are also a potential victim of another process hooking keys that got ahead of you and is not properly calling CallNextHookEx(). Tackle that with TaskMgr.exe, Processes tab and start killing processes. Start with anything that smells like vendor supplied shovelware, particularly if the keyboard has keys that don't fit the WM_APPCOMMAND command set and thus needs such a program to add gizmos.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Along the lines that Hans suggested, I would test it on a VM with a clean install of Windows to eliminate third party software. – Carey Gregory Aug 15 '12 at 03:26
  • Thanks. It turned out to be `Microsoft IntelliType Pro`. I killed the process and my code works as expected. – Gabriel McAdams Aug 15 '12 at 20:47
  • Question: Is there anything I can do about this? Any process that gets there first could do something before I have a chance to stop it. Is there a way to ensure that my code is the first to handle the message? – Gabriel McAdams Aug 15 '12 at 20:58