Windows 表单的 InputBinding
InputBinding for Windows Forms
我有一个现有的 WPF 应用程序,其中有一个相当高级的命令系统。我现在正在开发一个 WinForms 应用程序,我想在其中采用类似的命令系统。进展顺利,但我正在为快捷方式和键绑定翻译而苦苦挣扎。
对于 WPF 案例,我通过以下方法将命令的关键手势绑定到用户界面元素
public void BindKeyGestures(UIElement uiElement)
{
foreach (var keyboardShortcut in _keyboardShortcuts)
{
if (keyboardShortcut.KeyGesture != null)
{
uiElement.InputBindings.Add(new InputBinding(
_commandService.GetTargetableCommand(_commandService.GetCommand(keyboardShortcut.CommandDefinition)),
keyboardShortcut.KeyGesture));
}
}
}
有没有办法为 WinForms Control
添加 InputBindings
(我认为这不太可能,因为它是 WPF 构造),如果没有,我该如何添加无需显式覆盖包含形式的 ProcessCmdKey
的快捷方式?
有一些特定的控件(工具条项、菜单项)具有您可以使用的快捷键 属性(例如:https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripmenuitem.shortcutkeys(v=vs.110).aspx)。
对于其他控件,据我所知没有内置的东西,您需要自己创建一些系统。
这是您可以使用的简单扩展方法:
public static void Bind(this Control control, Keys shortcut, Action action)
{
Form form = control.FindForm();
if (form == null) throw new NullReferenceException($"Form not found for control: {control.Text ?? control.ToString()}");
form.KeyPreview = true;
form.KeyDown += (sender, args) =>
{
if (args.KeyData == shortcut) action();
};
}
需要在控件赋值给窗体后调用,否则会抛出异常。此外,这不包括取消订阅 KeyDown 事件,这将不那么容易实现(类似于缓存控件+快捷方式+委托三元组,然后在调用 Unbind 时取消订阅)。
上面的代码可以这样使用:
Button button = new Button { Text = "Click Me!" };
form.Controls.Add(button);
....
button.Bind(Keys.F | Keys.Control, () => doSomething()); //Will do something on Ctrl+F
我有一个现有的 WPF 应用程序,其中有一个相当高级的命令系统。我现在正在开发一个 WinForms 应用程序,我想在其中采用类似的命令系统。进展顺利,但我正在为快捷方式和键绑定翻译而苦苦挣扎。
对于 WPF 案例,我通过以下方法将命令的关键手势绑定到用户界面元素
public void BindKeyGestures(UIElement uiElement)
{
foreach (var keyboardShortcut in _keyboardShortcuts)
{
if (keyboardShortcut.KeyGesture != null)
{
uiElement.InputBindings.Add(new InputBinding(
_commandService.GetTargetableCommand(_commandService.GetCommand(keyboardShortcut.CommandDefinition)),
keyboardShortcut.KeyGesture));
}
}
}
有没有办法为 WinForms Control
添加 InputBindings
(我认为这不太可能,因为它是 WPF 构造),如果没有,我该如何添加无需显式覆盖包含形式的 ProcessCmdKey
的快捷方式?
有一些特定的控件(工具条项、菜单项)具有您可以使用的快捷键 属性(例如:https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripmenuitem.shortcutkeys(v=vs.110).aspx)。
对于其他控件,据我所知没有内置的东西,您需要自己创建一些系统。 这是您可以使用的简单扩展方法:
public static void Bind(this Control control, Keys shortcut, Action action)
{
Form form = control.FindForm();
if (form == null) throw new NullReferenceException($"Form not found for control: {control.Text ?? control.ToString()}");
form.KeyPreview = true;
form.KeyDown += (sender, args) =>
{
if (args.KeyData == shortcut) action();
};
}
需要在控件赋值给窗体后调用,否则会抛出异常。此外,这不包括取消订阅 KeyDown 事件,这将不那么容易实现(类似于缓存控件+快捷方式+委托三元组,然后在调用 Unbind 时取消订阅)。
上面的代码可以这样使用:
Button button = new Button { Text = "Click Me!" };
form.Controls.Add(button);
....
button.Bind(Keys.F | Keys.Control, () => doSomething()); //Will do something on Ctrl+F