How can I prevent RegisterHotKey from blocking the key for other applications?

3.9k views Asked by At

I am writing a win32 application that needs to take hotkeys while not on focus(it runs in the background without drawing a window). I use RegisterHotKey to assing a few keys but that blocks the for every other process. For example I assign the 'c' key and when I press it in notepad nothing happens.

3

There are 3 answers

0
Jonathan Potter On

RegisterHotKey() registers global hotkeys. Hotkeys are processed before regular keyboard input processing, meaning that if you register a hotkey successfully, pressing that key will result in you getting your hotkey message rather than the app with focus getting the normal WM_KEYDOWN/WM_CHAR messages. You have effectively blocked other apps from seeing that key press.

This is by design.

Obviously the solution to avoid clashes like you describe is to not register a hotkey that other applications may use. If you register C without any qualifiers as a hotkey, then no other program will see the C key being pressed. Instead you should use qualifiers like Ctrl/Shift/Alt to prevent your hotkey from interfering with the normal use of the keyboard.

There is no way to register a hotkey that's global unless some other program is active. If you want to achieve the situation where, say, your hotkey works while the desktop is active but nothing else is, you could use a message hook to inject code into the desktop's process (via SetWindowsHookEx()) and intercept key presses that way. But you can't do it with RegisterHotKey().

3
Hjorthenify On
GetAsyncKeyState()

can be used to determine if certain keys are pressed, even when the program is running in the background.

0
lion On

I just tried UnregisterHotKey(), simulated the key with keybd_event(), then RegisterHotKey() again. I don't recommend it as a production code, it's probably better to use hooks for that, but as a quick hack I just wanted to say that it works.