一、使用RoutedUICommand实现
假设您有一个window界面,在window中添加以下代码:
<Window.Resources>
<ResourceDictionary>
<RoutedUICommand x:Key="Boss" Text="老板键" />
</ResourceDictionary>
</Window.Resources>
<Window.InputBindings>
<!--按下F4键,执行老板键操作-->
<KeyBinding Key="F4" Command="{StaticResource Boss}"/>
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding x:Name="BossCommand" Command="{StaticResource Boss}"
CanExecute="BossCommand_CanExecute"
Executed="BossCommand_Executed"/>
</Window.CommandBindings>
在界面的.cs文件中,编写事件即可:
/// <summary>
/// 老板键的快捷键H操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BossCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
/// <summary>
/// 老板键的快捷键H操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BossCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (this.WindowState != WindowState.Minimized)
{
KeyboardEvents.OnKeyDown += KeyboardEvents_OnKeyDown;
this.Hide();
this.WindowState = WindowState.Minimized;
}
}
二、重载OnPreviewKeyDown方法来实现
/// <summary>
/// 使用这个快捷键的方法,可以替换RoutedUICommand的功能
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (e.Key == Key.F4)
{
if (this.WindowState == WindowState.Minimized)
{
this.Show();
this.WindowState = WindowState.Normal;
}
}
}
该重写方法,在界面 的.cs类中,即可找到。
三、使用EventManager实现快捷键功能
public class KeyboardEvents
{
public static event Action<KeyEventArgs> KeyDown;
static KeyboardEvents()
{
EventManager.RegisterClassHandler(typeof(Window), UIElement.KeyDownEvent, (KeyEventHandler)OnKeyDown);
}
private static void OnKeyDown(object sender, KeyEventArgs e)
{
if (KeyDown != null)
KeyDown(e);
}
}
编写一个上面的类,然后,找一个地方使用它,如图:
然后当您在界面上按下键盘时,都可以被OnKeyDown接收到。
三种方式都可以实现快捷键的操作,看您选择。
祝您用餐愉快。