1

I set up a low level keyboard hook in a worker thread that also runs a message loop. About 1/3 of my key strokes trigger the hook function and none release the GetMessage function in my message loop. Because of something related to the latter, messages aren't queued either (I just started working with Windows' message loop). What would cause only some keystroke to trigger a hook? And is there some setting/function call I'm missing to have the GetMessage to work correctly (according to this I'm not missing anything)?

This is my hook setup and message loop:

MIL_UINT32 MFTYPE MessageThread( void *v_DataEx )
{
MSG msg;

// Setup key listener
keyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
HINSTANCE instance = GetModuleHandle(NULL);
hookRes = SetWindowsHookEx( WH_KEYBOARD_LL, &KeyStrokeHook, instance, 0 );
HWND h = FindWindow( NULL, NULL );

while(GetMessage( &msg, h, 0, 0 ) > 0) // also tried with h = 0
{
    printf("Received message\n");
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
UnhookWindowsHookEx( hookRes );
return M_TRUE;
}

And my hook function:

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

if( wParam == WM_KEYDOWN ) // If key pressed, not released
{
    keyStroke = ((KBDLLHOOKSTRUCT *)lParam)->vkCode;

    SetEvent( keyEvent );
}
return CallNextHookEx( hookRes, code, wParam, lParam );
}
vlad417
  • 313
  • 1
  • 3
  • 10
  • Get rid of FindWindow(), you *must* create your own window for a low-level hook. CreateWindow/Ex call. – Hans Passant Apr 08 '14 at 13:07
  • Message loop should be `while(GetMessage(&msg, 0, 0, 0))` – David Heffernan Apr 08 '14 at 13:07
  • @DavidHeffernan Note the comment in my code. I already tried h=0, same result. – vlad417 Apr 08 '14 at 13:20
  • @HansPassant I'm trying `CreateWindow(NULL, NULL, WS_CHILD, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL)` but get a "The parameter is incorrect" (code 87) error. I also tried it with `instance` as the 2nd-to-last parameter, same error. None of the predefined system classes seem to match my need for the 1st parameter – vlad417 Apr 08 '14 at 13:41
  • @vlad417 in that case, you should register your own window class, but I suggest you try one thing at a time. Start by following a CreateWindow example, then add the low-level hook. Once that is working you can tweak the window creation. – Luis Apr 08 '14 at 14:06
  • @vlad417 I'm telling you should pass `0` for the second parameter. I'm not claiming that will fix your problem. If you don't want help, I'll gladly leave you alone. – David Heffernan Apr 08 '14 at 14:06
  • Probably not the right solution, but using `PeekMessage` instead which does not block seemed to work. Although it always returns `0` indicating there are no messages, the hook seems to work correctly. – Lonami Oct 18 '22 at 10:52

0 Answers0