简体   繁体   中英

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();
        }
    }
}

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM