如何在WPF中按下快捷键(例如 Ctrl + O )(独立于任何特定控件)?
我尝试捕获KeyDown
,但KeyEventArgs
并未告诉我 Control 或 Alt 是否已关闭。
答案 0 :(得分:10)
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
// CTRL is down.
}
}
答案 1 :(得分:1)
我终于想出了如何使用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
}