Question

I am having a problem trying to use a keyboard hook. What I am trying to do (and does) is from any window/ focus, I can hit a key that runs a function (that moves the mouse and clicks.)

It works just fine from the front, but as soon as I start doing something else, everything acts strange (even when after closing the problem.)

On firefox it will have a "select and highlight all to where the mouse is when I click"; if I try to type, all numeric characters come out as if the shift button was down and no way around it. If I click on my compiler on the taskbar (wxDev C++), it automatically starts a new instance of the program.

That is just the start of the problems, I have a restart my computer to get normal behavior again.

I figure that I might be using it wrong:

In int WinMain:

keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hThisInstance, 0);

In the main procedure:

case WM_KEY_WPARAM_VK: 
keyid = wParam; // 65 == 'a'
letterid = keyid - 65;
if ('a'+letterid == 'q') {  DoFunction(); }
return 0;

So that when I hit q on the keyboard, the function is called.

This is the procedure, I am trying to not lock the keyboard from typing (so I added the extra line.) I cannot figure this out...

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam ) {
  KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
  // When a key is pressed
  if (WM_KEYDOWN == wParam) {
    PostMessage(hWnd, WM_KEY_WPARAM_VK, pKeyBoard->vkCode, 0);
    CallNextHookEx(keyboardHook, pKeyBoard->vkCode, 0, 0);
  }
}

Thanks for reading.

Was it helpful?

Solution

You need to put the CallNextHookEx function outside the if statement! (and also update it to properly pass wParam and lParam to the next hook)

return CallNextHookEx(keyboardHook, pKeyBoard->vkCode, wParam, lParam);

The way you currently have it, your code will block all "key-up" strokes from the rest of the OS, hence the strange behavior.

It's absolutely imperative that CallNextHookEx gets called regardless of what you do within the hook. I would also avoid performing any lengthy (blocking) operations while inside your hook.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top