Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle a shortcut key in every WPF window?

I want to open the help file to a page based on some custom logic. How can I handle the user pressing F1 on all of my windows (main window and modal dialogs) ?

I know how to handle F1 in a single window, but can this be done globally, so I don't have to add the same code to all of my windows ?

Below is the test with which I've tried out that F1 does not work on the child window.

Window1.xaml:

<Window x:Class="WpfApplication2.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Help"
                        Executed="CommandBinding_Executed"/>
    </Window.CommandBindings>
    <Grid>
        <Button Content="Open a new window"
                Click="Button_Click"/>
    </Grid>
</Window>

Window1.xaml.cs:

using System.Windows;
using System.Windows.Input;

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

        void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Help");
        }

        void Button_Click(object sender, RoutedEventArgs e)
        {
            new Window().ShowDialog();
        }
    }
}
like image 346
Jeno Csupor Avatar asked Jul 17 '09 16:07

Jeno Csupor


People also ask

How do you implement keyboard shortcuts?

Begin keyboard shortcuts with CTRL or a function key. Press the TAB key repeatedly until the cursor is in the Press new shortcut key box. Press the combination of keys that you want to assign. For example, press CTRL plus the key that you want to use.

Which shortcut key combination will you use for window operation?

Ctrl+N: Open a new browser window. Ctrl+T: Open a new browser tab. Ctrl+D: Bookmark the current page. Ctrl+B: View bookmarks.

How do I assign keyboard shortcuts in Visual Studio?

On the menu bar, choose Tools > Options. Expand Environment, and then choose Keyboard. Optional: Filter the list of commands by entering all or part of the name of the command, without spaces, in the Show commands containing box. In the list, choose the command to which you want to assign a keyboard shortcut.


1 Answers

I've found the answer on this page. That is, put this in the main window's constructor for example:

CommandManager.RegisterClassCommandBinding(typeof(Window),
    new CommandBinding(ApplicationCommands.Help,
        (x, y) => MessageBox.Show("Help")));
like image 196
Jeno Csupor Avatar answered Oct 27 '22 21:10

Jeno Csupor