当应用程序未聚焦时监听按键
我有一个应用程序(C# 4.0-WPF),它是隐藏的,可以通过单击系统托盘图标或我创建的其他框架(停靠在左侧和最上面的小框架)来显示。
我的客户想要添加一种新的方式来显示应用程序:按下“F”键(例如 F9)时。
当应用程序不是当前窗口/或未聚焦时,我如何知道在我的应用程序中用户是否按下此键?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只需要几个全局热键,则全局键盘挂钩不是正确的解决方案。
使用
WH_KEYBOARD
的全局键盘钩子意味着您的dll将被注入到接收按键的每个进程中。它根本不应该在托管代码中使用,因为 CLR 相对较重,可能会导致版本冲突。此代码注入对于防病毒软件来说也很可疑,可能会阻止它。
对于托管代码来说,使用 WH_KEYBOARD_LL 的低级键盘挂钩是更好的选择,因为它会在您自己的应用程序中处理键盘事件。但它仍然要求每个键盘事件都由您的线程处理。
这会增加按下按键和目标应用程序接收按键之间的时间。
如果具有比您的应用程序更高的 CPU 优先级的应用程序导致其 CPU 时间匮乏,则情况尤其糟糕。在这种情况下,延迟可能会达到几秒钟,将许多按键聚集在一起。一些(写得不好的)游戏会像这样工作,在这种情况下无法玩。
Windows API函数
RegisterHotKey
是用于全局热键的正确函数。Windows 将为您进行过滤,并且仅在按下其中一个注册键时通知您的应用程序,因此您不必处理所有这些键。
正如您计划的那样,使用简单的 F 键作为全局热键是有问题的,因为它经常与具有焦点的应用程序的本地热键发生冲突。因此,您应该配置全局热键,以便用户可以避免与其常用应用程序发生冲突。
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.