0

I'm trying to create a hook to a keyboard event but the hook is never called on a key stroke. I set the hook with:

HHOOK hookRes = SetWindowsHookEx( WH_KEYBOARD, &KeyStrokeHook, NULL, GetCurrentThreadId() );

And the callback function is:

LRESULT CALLBACK KeyStrokeHook( _In_  int code, _In_  WPARAM wParam, _In_  LPARAM lParam )
{
if( code < 0 )
    return CallNextHookEx( NULL, code, wParam, lParam );

if( lParam & 0x80000000 == 0 ) // If key pressed, not released
{
    keyStroke = wParam;

    SetEvent( keyEvent );
}
return CallNextHookEx( NULL, code, wParam, lParam );
}

hookRes has a valid hook, but the hook function is never called.

Can the hook be triggered if the thread that set the hook is currently blocked on a mutex?

vlad417
  • 313
  • 1
  • 3
  • 10
  • `WH_KEYBOARD` is only triggered when a keyboard event (`WM_KEYDOWN` or `WM_KEYUP`) is processed from the message queue. So, your hook will only get called when the specific thread receives and processes keyboard input - certainly not if, for example, the thread is blocked by a mutex. – jlahd Apr 07 '14 at 15:27
  • I certainly don't want a thread sitting in a while(true) loop just to listen to keyboard events. Is there a better way for the thread to trigger the hook function than sitting in such a loop? – vlad417 Apr 07 '14 at 15:40
  • Sitting in a while(true) loop is a sure way of *not* getting any hook callbacks. Mind you, you only get the callbacks if you receive *and process* keyboard messages. If you are sitting in a loop, you are certainly *not* processing messages. Could you elaborate a bit on what you are trying to accomplish? – jlahd Apr 07 '14 at 15:54
  • I have n threads that I'd like to associate with a digit on the keyboard, so when their number is pressed the `keyEvent` is signaled, they wake up, check if their number was pressed, if not then go back to waiting on `keyEvent`, else do some processing – vlad417 Apr 07 '14 at 16:34
  • 1
    OK. Hooks do not work that way. The hook is called in the context of the thread that is processing input (or, in the case of cross-process hooks, an arbitrary thread) - not in the context of the thread that set the hook. I recommend you set a WH_LL_KEYBOARD hook and, in its hook procedure, check the digit that was pressed and then signal the correct waiting thread. – jlahd Apr 07 '14 at 17:07
  • Sort of works, having [this problem](http://stackoverflow.com/questions/22937950/low-level-keyboard-hook-called-intermittently-getmessage-never-returns) now – vlad417 Apr 08 '14 at 13:55

0 Answers0