views:

21

answers:

1

In order to use SetWindowsHookEx in a GUI application, you usually want in the bottom line to have a function in your thread called whenever an event has occurred.

So for instance if I'm making a software to show all keys being pressed on the system, I want that somehow my GUI app will have the function AddKeyToList(int vkeycode) called whenever a key is being pressed.

I'm not an expert in the internals of Windows, but if I understand the documentation correctly, hooks installed by SetWindowsHookEx are being called in the context of the thread which caused the event they're hooking. So in order to do what I described, one needs to:

  1. Create a DLL which will contain the hook function, and create there a shared memory region that all threads would share and communicate with each other through it.

  2. Create a pInvoke like mechanism in both the hook function and the GUI program. In our example the hook function will send the key pressed to our GUI program, and the GUI program will invoke in its own context the AddKeyToList function.

This is incredibly complex for a relatively simple class (compare to the XRecord extension in the unix world), and its maybe even impossible if you use something like Qt.

Is there any library (preferably open source) which already implemented those mechanisms, and enable me to use a "facade" which, for example, will invoke a function in my thread context whenever a WH_KEYBOARD_LL occurs?

Am I correct with my analysis, or is there a simpler method to achieve what I described?

Can the Qt library help me with this task?

+1  A: 

That's already the default behavior for a WH_KEYBOARD_LL hook. The callback is called in the same thread that called SetWindowsHookEx(). That thread must also pump a message loop for this to work properly, automatic when you use your UI thread. And the callback code doesn't need to be present in a DLL either, it is not a global hook that requires DLL injection.

No extra work needs to be done.

Hans Passant
+1 for mentioning undocumented fact about not needing callback to be in DLL
bowenl2