Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Short Cut Key to a button in WPF

Tags:

wpf

c#-3.0

People also ask

How do I assign a shortcut to a button?

Right-click the control for which you want to set a keyboard shortcut, and then click Control Properties on the shortcut menu. Click the Advanced tab. In the Access key box, type a character. An access key is simply a keyboard shortcut that uses the ALT key as part of the shortcut.


This is kind of old, but I ran into the same issue today.
I found that the simplest solution is to just use an AccessText element for the button's content.

<Button Command="{Binding SomeCommand}">
    <AccessText>_Help</AccessText>
</Button>

When you press the Alt key, the 'H' will be underlined on the button.
When you press the key combination Alt+H, the command that is bound to the button will be executed.

http://social.msdn.microsoft.com/Forums/vstudio/en-US/49c0e8e9-07ac-4371-b21c-3b30abf85e0b/button-hotkeys?forum=wpf


Solution for key binding (+ button binding) with own commands:

The body of XAML file:

<Window.Resources>
    <RoutedUICommand x:Key="MyCommand1" Text="Text" />
    <RoutedUICommand x:Key="MyCommand2" Text="Another Text" />
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource MyCommand1}" 
                    Executed="FirstMethod" />
    <CommandBinding Command="{StaticResource MyCommand2}" 
                    Executed="SecondMethod" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Key="Z" Modifiers="Ctrl" Command="{StaticResource MyCommand1}" />
    <KeyBinding Key="H" Modifiers="Alt" Command="{StaticResource MyCommand2}" />
</Window.InputBindings>

<Grid>
    <Button x:Name="btn1" Command="{StaticResource MyCommand1}" Content="Click me" />
    <Button x:Name="btn2" Command="{StaticResource MyCommand2}" Content="Click me" />
</Grid>

and .CS file:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    public void FirstMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn1
    }

    public void SecondMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn2
    }
}

The shortcut is just h for your sample code. On

To initially show underlines for shortcuts is a Windows setting and not controlled by an app. In Windows XP, go to Display Properties -> Appearance -> Effects and you will see a checkbox labeled "Hide underlined letters for keyboard navigation until I press the Alt key". For Vista/Win7 I think they moved that setting somewhere else.


The simplest solution I've found is to stick a label inside the button:

<Button Name="btnHelp"><Label>_Help</Label></Button>