在整个应用程序中捕获按键

有可能,捕获(我想在app.xaml.cs中的某个地方)任何键,如果按下打开的窗口?

感谢帮助!

你可以使用像这个gist这样的东西来注册一个全局钩子。 在应用程序运行时按下给定键时,它将触发。 您可以在App类中使用它,如下所示:

 public partial class App { private HotKey _hotKey; protected override void OnActivated(EventArgs e) { base.OnActivated(e); RegisterHotKeys(); } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); UnregisterHotKeys(); } private void RegisterHotKeys() { if (_hotKey != null) return; _hotKey = new HotKey(ModifierKeys.Control | ModifierKeys.Shift, Key.V, Current.MainWindow); _hotKey.HotKeyPressed += OnHotKeyPressed; } private void UnregisterHotKeys() { if (_hotKey == null) return; _hotKey.HotKeyPressed -= OnHotKeyPressed; _hotKey.Dispose(); } private void OnHotKeyPressed(HotKey hotKey) { // Do whatever you want to do here } } 

是的,不是。

焦点在处理给定键的顺序中起作用。 捕获初始按键的控件可以选择不通过键,这将禁止您在最高级别捕获它。 此外,在.NET框架中有一些控件可以在某些情况下吞下某些键,但是我无法回想起特定的实例。

如果您的应用程序很小并且深度只不过是带按钮的窗口,那么这肯定是可以实现的,并且将遵循标准方法来捕获WPF应用程序中的击键。

 protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) myVariable = true; if (ctrl && e.Key == Key.S) base.OnKeyDown(e); } protected override void OnKeyUp(KeyEventArgs e) { if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) myVariable = false; base.OnKeyUp(e); } 

如果您的应用程序很大,您可以尝试全局钩子 ,如此处详述,但要了解上述警告仍然存在。

有一个更好的办法。 在MS论坛上找到了这个 。 奇迹般有效。

将此代码放在Application启动中:

 EventManager.RegisterClassHandler(typeof(Window), Keyboard.KeyUpEvent,new KeyEventHandler(keyUp), true); private void keyUp(object sender, KeyEventArgs e) { //Your code... }