如何使用 WPF 和 .NET 3.5 注册全局热键以说出 CTRL+SHIFT+(LETTER)? [英] How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

查看:365
本文介绍了如何使用 WPF 和 .NET 3.5 注册全局热键以说出 CTRL+SHIFT+(LETTER)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WPF 在 C# 中构建一个应用程序.如何绑定一些键?

I'm building an application in C# using WPF. How can I bind to some keys?

另外,如何绑定到 Windows 键?

推荐答案

我不确定你所说的全局"是什么意思.在这里,但在这里(我假设您的意思是应用程序级别的命令,例如 Save All 可以通过 Ctrl + Shift + S.)

I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S.)

您可以找到您选择的全局 UIElement,例如,顶层窗口是您需要此绑定的所有控件的父级窗口.由于冒泡"在 WPF 事件中,子元素上的事件将一直冒泡到控件树的根.

You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree.

现在,首先你需要

  1. 使用 InputBinding 像这样将 Key-Combo 与命令绑定
  2. 然后您可以通过 CommandBinding 将命令连接到您的处理程序(例如,由 SaveAll 调用的代码).
  1. to bind the Key-Combo with a Command using an InputBinding like this
  2. you can then hookup the command to your handler (e.g. code that gets called by SaveAll) via a CommandBinding.

对于 Windows 键,您使用正确的 Key 枚举成员,Key.LWinKey.RWin

For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin

public WindowMain()
{
   InitializeComponent();

   // Bind Key
   var ib = new InputBinding(
       MyAppCommands.SaveAll,
       new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
   this.InputBindings.Add(ib);

   // Bind handler
   var cb = new CommandBinding( MyAppCommands.SaveAll);
   cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );

   this.CommandBindings.Add (cb );
}

private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)
{
  // Do the Save All thing here.
}

这篇关于如何使用 WPF 和 .NET 3.5 注册全局热键以说出 CTRL+SHIFT+(LETTER)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆