[英]C# Hotkeys while holding Control
I am trying to add some hotkeys to my Window application so that if i press Ctrl+Q it will perform an action. 我正在尝试向Windows应用程序中添加一些热键,以便如果我按Ctrl + Q它将执行一个操作。 I can't quite figure this out.
我不太明白这一点。 I looked through stack overflow and MSDN but i can't find the answer i need.
我查看了堆栈溢出和MSDN,但找不到所需的答案。 So this is what i currently have
这就是我目前拥有的
xaml: xaml:
<Grid KeyDown="Grid_KeyDown" KeyUp="Grid_KeyUp">
<Menu Height="20" VerticalAlignment="Top" >
<MenuItem Name="MenuItemFile" Header="File" >
<MenuItem Name="CloseApp" Header="Close" Icon="" Click="CloseApp_Click" AutomationProperties.AcceleratorKey="Control L" InputGestureText="Ctrl+X"/>
</MenuItem>
c# C#
private void Grid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl)
{
switch (e.Key)
{
case Key.L:
This.Close();
break;
}
}
}
You can simply do that by 您可以简单地通过
private void Grid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Q && e.Modifiers == Keys.Control)
{
// do stuff
}
}
This is in a different direction now, but WPF has Commands which can help you with this as well. 现在这是一个不同的方向,但是WPF的命令也可以帮助您。 You can define a
RoutedCommand
or RoutedUICommand
and append EventHandlers to the CanExecute
and Executed
events. 您可以定义
RoutedCommand
或RoutedUICommand
并将EventHandlers附加到CanExecute
和Executed
事件。 Commands can also have KeyBindings in combination with modification keys like Ctrl
or Shift
. 命令还可以具有KeyBindings以及
Ctrl
或Shift
类的修改键。 This is particularly useful when you want to structure a bigger application. 当您要构建更大的应用程序时,这特别有用。
Here are some details on How to: Create a RoutedCommand and an overview about commands 以下是有关如何:创建RoutedCommand的一些详细信息以及有关命令的概述
You can bind a key to a command in your XAML: 您可以将密钥绑定到XAML中的命令:
<Window.InputBindings>
<KeyBinding Key="Q" Modifiers="Control" Command="ApplicationCommands.Close"/>
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandHandler"/>
</Window.CommandBindings>
Then define what the command should do in your code-behind: 然后在后面的代码中定义命令应执行的操作:
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
Or map it to a command in your ViewModel, if you're using the MVVM pattern. 如果使用的是MVVM模式,也可以将其映射到ViewModel中的命令。
Can you use ALT instead of CTRL? 可以使用ALT代替CTRL吗? Is so, give this a try - it is built right in:
是的,请尝试一下-它内置于:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.