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.
Asked
Active
Viewed 1.1k times
0
-
2You 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 Answers
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>
-
-
@AComputert: write a subclass which is inherited from Window or UserControl. Then implement these in that `YourWindow` and then use it instead of any window you want. – Zhr Saghaie Jun 07 '15 at 12:10
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