Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Keyboard Shortcuts

Tags:

c#

wpf

I currently use the onKeyDown event and an if/else statement to create keyboard shortcuts:

if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {

} else if (e.Key == Key.Tab) {

} ...

However, if I have quite a few more keyboard shortcuts, this gets messy.

Is there a better implementation?

like image 434
Jiew Meng Avatar asked Aug 26 '10 10:08

Jiew Meng


People also ask

Can I create my own keyboard shortcuts?

Once the program is on the taskbar: Left-click “properties” Click on the text box that says “shortcut key” Type in your desired keyboard combination by pressing the keys. Once completed, click “ok”

What is F1 f2 f3 F4 f5 f6 f7 f8 f9 f10 F11 F12?

The function keys or F-keys on a computer keyboard, labeled F1 through F12, are keys that have a special function defined by the operating system, or by a currently running program. They may be combined with the Alt or Ctrl keys.

What are keyboard shortcuts?

A hot key is a key or a combination of keys on a computer keyboard that, when pressed at one time, performs a task (such as starting an application) more quickly than by using a mouse or other input device. Hot keys are sometimes called shortcut keys. Hot keys are supported by many operating system and applications.


1 Answers

You should look at implementing <CommandBindings> and <InputBindings>:

<Window.CommandBindings>
    <CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Command="Settings" Key="S" Modifiers="Alt" />
</Window.InputBindings>

Your <Button> then becomes:

<Button Height="50" Width="50" Margin="50,5,0,0" Command="Settings" />

The SettingsCanExecute method determines when the button is enabled and the SettingsExecuted method is called when the button is pressed or the key combination struck.

You then don't need the KeyDown handler.

There's a full tutorial on Switch On The Code.

More information on CommandBindings and InputBindings can be found on the MSDN.

like image 63
ChrisF Avatar answered Sep 21 '22 10:09

ChrisF