Jesus Fernandez
Jesus Fernandez

Reputation: 1290

WH_KEYBOARD_LL hook only in my process main thread

Is it possible to have a WH_KEYBOARD_LL hook that only calls the hook function when my application/thread has the focus? Currently I'm receiving calls even when the application is not active.

Upvotes: 0

Views: 264

Answers (2)

Hans Passant
Hans Passant

Reputation: 941397

Sure, the 4th argument to SetWindowsHookEx() can be a thread ID to make it selective. Pass the one for your UI thread, get it by calling GetCurrentThreadId().

Do note that this is not normally very useful, you can intercept keyboard messages in your message loop just as easily. Every GUI class library supports this, required to implement shortcut keystrokes. Even the winapi has this, TranslateAccelerator(). Strongly recommended, debugging a hook is very painful since a breakpoint in the hook callback or any function called by your callback will cause the keyboard to seize up for 5 seconds and your hook to be destroyed.

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612934

There's no way for you to install a hook and also apply some form of filter to suppress it firing in certain states. Once it is installed, it will fire.

So, either do nothing in your hook function when your application is inactive, or remove the hook when it becomes inactive. Or, do away with the hook altogether, and respond to the messages that arrive in your message queue.

Upvotes: 1

Related Questions