Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...