x3r5d4
x3r5d4

Reputation: 37

WH_KEYBOARD_LL hook not called

I'm having some problems with a WH_KEYBOARD_LL hook :

The reason why I'm using a global LL hook is not important I just need it for my app (I tried other types of hooks but they didn't work for me).

The hook function is in a dll, the dll is loaded on the application start-up and the hook is set also on start-up from the main thread. This works perfectly. The problem appears when I need to deactivate the hook and reactivate it back. If I do that from the main thread of the application it works ok , but what I need is to do this from a timer, and here things go wrong. I use the timer to check if my app's window is the foreground window (the active window), if so the hook is activated and if not the hook is deactivated. The return value of SetWindowsHookEx when called from the timer is always ok (not null) which according to MSDN means that the hook was successfully set, but my hook function never gets called.

Here is how I set my hook:

SetWindowsHookEx(WH_KEYBOARD_LL, keyboardHookProcedure,
                 GetModuleHandle(curModule.ModuleName), 0);

Has anyone ever experienced this??

My only guess is that my hook function is in a dll and the timer callback is from another dll, does this has anything to do with my problem??

Upvotes: 1

Views: 2900

Answers (3)

Hans Passant
Hans Passant

Reputation: 942197

The hook callback is made on the same thread that called SetWindowsHookEx(). That bit of magic requires that thread to pump a message loop. Which is the rub, your timer callback method is called from a threadpool thread. It doesn't pump, it's not even around long enough to ever be able to get the hook callback.

Invoke to your UI thread or use a synchronous timer. Or consider just temporarily disabling whatever you do in the hook callback instead of completely disabling or replacing the hook, that certainly makes most sense.

Upvotes: 6

Martin Stone
Martin Stone

Reputation: 13027

You could check the foreground window in your hook function instead, and get rid of the timer thread altogether. That's what I do in TouchCursor. You can look at my code on SourceForge -- Line 553 for the hook function.

Upvotes: 0

Martin Stone
Martin Stone

Reputation: 13027

For what it's worth, I use GetModuleHandle(0) for SetWindowsHookEx in my code. I have no idea if this is your problem -- my code is single-threaded.

Upvotes: 0

Related Questions