listen for a key when the application is not focused

Global keyboard hooks are not the right solution if you only want a few global hotkeys.

  • A global keyboard hook using WH_KEYBOARD means that your dll will be injected into every process that receives key presses. It should not be used at all in managed code, since the CLR is relatively heavy weight and may cause version conflicts.

    This code injection will also look suspicious to anti-virus software, which might block it.

  • A low level keyboard hook using WH_KEYBOARD_LL is a better choice for managed code, since it processes the keyboard events in your own application. Still it requires that every keyboard event is handled by your thread.

    This increases the time between a key being pressed and the target application receiving it.

    This is particularly bad if an application with higher CPU priority than your application starves it of CPU time. In that case the latency can reach several seconds, bunching many keypresses together. Some (badly written) games work like that and become unplayable in such a situation.

  • The windows API function RegisterHotKey is the proper function to use for global hotkeys.

    Windows will do the filtering for you, and only notify your application if one of the registered keys has been pressed, so you don’t have to process all of them.

Using a simple F-Key as global hotkey, as you plan on doing, is problematic since it often collides with a local hotkey of the application that has focus. So you should make global hotkeys configurable, so the user can avoid collisions with their commonly used applications.

Leave a Comment