listen for a key when the application is not focused

自古美人都是妖i 提交于 2019-11-27 15:32:40

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!