【发布时间】:2010-10-24 08:22:31
【问题描述】:
如何检测在 WPF 中按下诸如 Ctrl + O 之类的快捷键(独立于任何特定控件)?
我尝试捕获 KeyDown,但 KeyEventArgs 并没有告诉我 Control 或 Alt 是否已关闭。
【问题讨论】:
标签: .net wpf keyboard-shortcuts hotkeys
如何检测在 WPF 中按下诸如 Ctrl + O 之类的快捷键(独立于任何特定控件)?
我尝试捕获 KeyDown,但 KeyEventArgs 并没有告诉我 Control 或 Alt 是否已关闭。
【问题讨论】:
标签: .net wpf keyboard-shortcuts hotkeys
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
// CTRL is down.
}
}
【讨论】:
我终于想出了如何使用 XAML 中的命令来做到这一点。不幸的是,如果您想使用自定义命令名称(不是 ApplicationCommands.Open 等预定义命令之一),则必须在代码隐藏中定义它,如下所示:
namespace MyNamespace {
public static class CustomCommands
{
public static RoutedCommand MyCommand =
new RoutedCommand("MyCommand", typeof(CustomCommands));
}
}
XAML 是这样的...
<Window x:Class="MyNamespace.DemoWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
Title="..." Height="299" Width="454">
<Window.InputBindings>
<KeyBinding Gesture="Control+O" Command="local:CustomCommands.MyCommand"/>
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommands.MyCommand" Executed="MyCommand_Executed"/>
</Window.CommandBindings>
</Window>
当然你还需要一个处理程序:
private void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Handle the command. Optionally set e.Handled
}
【讨论】: