Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listen for a key when the application is not focused

I've an application(C# 4.0-WPF), which is hidden and can be displayed by clicking on the systray icon or on an other frame I created(small frame which is docked left and topmost).

My customer wants to add a new way to display the application: When pressing on a "F" key (e.g. F9).

How do I know in my application if the user presses this key when the application is not the current window /or is not focused?

like image 390
J4N Avatar asked Feb 21 '11 12:02

J4N


1 Answers

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.

like image 191
CodesInChaos Avatar answered Nov 19 '22 05:11

CodesInChaos