0

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.

AComputer
  • 519
  • 2
  • 10
  • 21
  • 2
    You can use underscore `_` in button contents and it will trigger with `Alt` key. also see: http://stackoverflow.com/questions/3246134/assign-short-cut-key-to-a-button-wpf – Habib Mar 11 '13 at 07:57
  • This similar question might be of interest: http://stackoverflow.com/questions/612966/keyboard-events-in-a-wpf-mvvm-application – André C. Andersen Mar 11 '13 at 07:57

2 Answers2

2

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

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>
rene
  • 41,474
  • 78
  • 114
  • 152
Jonas W
  • 3,200
  • 1
  • 31
  • 44
2

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:

<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>
DevT
  • 4,843
  • 16
  • 59
  • 92