【问题标题】:How can I handle a shortcut key in every WPF window?如何处理每个 WPF 窗口中的快捷键?
【发布时间】:2010-11-11 18:50:45
【问题描述】:

我想将帮助文件打开到基于一些自定义逻辑的页面。如何处理用户在我的所有窗口(主窗口和模式对话框)上按 F1?

我知道如何在单个窗口中处理 F1,但这可以在全局范围内完成,因此我不必向所有窗口添加相同的代码吗?

以下是我尝试过的 F1 在子窗口上不起作用的测试。

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

【问题讨论】:

    标签: c# wpf keyboard-shortcuts hotkeys


    【解决方案1】:

    我在this 页面上找到了答案。 也就是说,把它放在主窗口的构造函数中,例如:

    CommandManager.RegisterClassCommandBinding(typeof(Window),
        new CommandBinding(ApplicationCommands.Help,
            (x, y) => MessageBox.Show("Help")));
    

    【讨论】:

    • 它也适用于子控件。 IE。如果选择了子控件,那么如果它的类型已注册,它将处理 F1,否则将触发窗口处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多