I’m trying to write an application that responds whenever the Shift key is pressed, no matter what application currently has focus.
I tried this with SetWindowsHookEx() and with GetKeyboardState(), but both of these only work when the application’s window has focus. I need it to work globally.
How do I do this?
None of the provided answers helped me solve my problem, but I found the answer myself. Here it is.
Using
SetWindowsHookEx()withWH_KEYBOARD_LLwas the correct approach. However, the other parameters toSetWindowsHookEx()are unintuitive:dwThreadId, needs to be 0.hMod, needs to point to some DLL. I usedUser32, which is a DLL that is always loaded anyway and is used by allprocesses with a GUI. I got this idea from a CodeProject post about this.
Thus, the code looks a bit like this:
The documentation is unclear about the second-last parameter. It says:
It doesn’t state that this only applies to some types of hooks, but not to
WH_KEYBOARD_LLandWH_MOUSE_LL.