wpf 全局 Windows 按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11752254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global Windows Key Press
提问by Ionic? Biz?u
I have a simple WPF application and I need to capture F1 key pressed in Windows (Operation System), even if my WPF window is minimized, or it isn't activated.
我有一个简单的 WPF 应用程序,我需要捕获在 Windows(操作系统)中按下的 F1 键,即使我的 WPF 窗口已最小化或未激活。
I have problems with detecting this. I searched on Internet and I found many results, but they didn't helped me.
我在检测这个方面有问题。我在互联网上搜索并找到了很多结果,但它们并没有帮助我。
For detecting a key pressed inside of application I used this simple code:
为了检测应用程序内部按下的键,我使用了这个简单的代码:
AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)KeyPressed);
private void KeyPressed(object sender, KeyEventArgs e)
{
if (e.Key == Key.F1)
{
//my code went here
}
}
But this doesn't work when my window isn't activated.
但是当我的窗口没有被激活时这不起作用。
So, my question is: how to detect global key press?
所以,我的问题是:如何检测全局按键?
I repeat: It is a WPF application.
我再说一遍:这是一个 WPF 应用程序。
回答by Ria
No need to Keyboard Hooking. Just use RegisterHotKey(Defines a system-wide hot key) and UnregisterHotKeyfrom Windows API. Try using these in C# from pinvoke.netor these tutorials:
没有必要Keyboard Hooking。只需使用RegisterHotKey(定义系统范围的热键)和UnregisterHotKey来自 Windows API。尝试在来自pinvoke.net或这些教程的C# 中使用这些:
- Global Hotkeys: Register a hotkey that is triggered even when form isn't focused.
- Simple steps to enable Hotkey and ShortcutInput user control
There is a sample in Microsoft Forums.
Microsoft 论坛中有一个示例。
You can use these modifiers and Virtual-Key Codes:
您可以使用这些修饰符和虚拟键代码:
MOD_ALT (0x0001) MOD_CONTROL (0x0002) MOD_NOREPEAT (0x4000) MOD_SHIFT (0x0004) MOD_WIN (0x0008)
for example F1 key is VK_F1 (0x70).
例如 F1 键是VK_F1 (0x70).
回答by G.Y
When your application is not in focus - messags pump will not get anything - you need to use system level API's for hooking keys. (try to search info on SetWindowsHookEx)
当您的应用程序不在焦点上时 - 消息泵不会得到任何东西 - 您需要使用系统级 API 来挂钩键。(尝试在 SetWindowsHookEx 上搜索信息)

