wpf 给按钮添加快捷键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15333587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:00:14  来源:igfitidea点击:

Add Short Cut Key to button

c#wpf

提问by AComputer

How Can I Add Short Cut Key To button in wpf? I have three window with New Button and i want to add Ctrl+N or etc short cut to all of them.

如何在 wpf 中添加快捷键到按钮?我有三个带有新按钮的窗口,我想为所有这些窗口添加 Ctrl+N 或其他快捷方式。

回答by Jonas W

Here is a great tutorial for this : https://web.archive.org/web/20150430045153/http://tech.pro:80/tutorial/839/wpf-tutorial-command-bindings-and-custom-commands

这是一个很好的教程:https: //web.archive.org/web/20150430045153/http: //tech.pro: 80/tutorial/ 839/wpf-tutorial- command-bindings-and-custom-commands

Sample (taken from link above)

示例(取自上面的链接)

<Window x:Class="CustomCommandTest.CommandWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Custom Command Test" Height="300" Width="300">

  <Window.CommandBindings>
    <CommandBinding Command="Help" 
        CanExecute="HelpCanExecute"
        Executed="HelpExecuted" />
  </Window.CommandBindings>

  <Window.InputBindings>
    <KeyBinding Command="Help" Key="H" Modifiers="Ctrl"/>
    <MouseBinding Command="Help" MouseAction="LeftDoubleClick" />
  </Window.InputBindings>

  <StackPanel>
    <Button Command="Help" Content="Help Command Button" />
    <Button Content="My Command" x:Name="MyCommandButton" />
  </StackPanel>
</Window>

回答by DevT

you can do it as following method too. in form write method indicating short cut keys.

您也可以按照以下方法进行操作。在形式写方法指示快捷键。

private void shortcutKey_Click(object sender, System.Windows.Input.KeyEventArgs e)
{
    if ((e.Key == Key.N) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
        ProjMnuBtn_AddProj_Click(null, null);
}

then in xaml file you need to set it as follows:

然后在 xaml 文件中,您需要将其设置如下:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="1280" Height="920" KeyUp="shortcutKey_Click">

</Window>