【问题标题】:How is "Esc" key handled in WPF Window?WPF 窗口中如何处理“Esc”键?
【发布时间】:2010-04-19 02:18:15
【问题描述】:

我希望 Escape 键关闭我的 WPF 窗口。但是,如果有一个控件可以使用该 Escape 键,我不想关闭窗口。按下 ESC 键时如何关闭 WPF 窗口有多种解决方案。例如。 How does the WPF Button.IsCancel property work?

但是,此解决方案会关闭窗口,而不考虑是否存在可以使用 Escape 键的活动控件。

例如。我有一个带有 DataGrid 的窗口。 dataGrid 上的一列是组合框。如果我要更改 ComboBox,然后点击 Escape,则控件应该退出组合框的编辑(正常行为)。如果我现在再次点击 Escape,那么窗口应该关闭。我想要一个通用的解决方案,而不是编写大量的自定义代码。

如果你能在 C# 中提供解决方案,那就太好了。

【问题讨论】:

    标签: wpf window esc-key


    【解决方案1】:

    您应该只使用KeyDown 事件而不是PreviewKeyDown 事件。如果Window 的任何子级处理事件,它不会冒泡到窗口(@98​​7654324@ 隧道从Window 向下),因此不会调用您的事件处理程序。

    【讨论】:

    • 这对我有用。然而,并非在所有情况下。特别是,我正在使用 Telerik 的 DataGrid 控件。如果一个单元格有一个组合框,并且它被展开,然后我点击 Escape,则 Escape 键不会传播到窗口。但是,如果 ComboBox 未展开,而是处于编辑模式,则传播 Escape 键。我认为这可能是控件的错误。您的建议确实有效。
    【解决方案2】:

    可能有更简单的方法,但您可以使用哈希码来实现。 Keys.Escape 是另一种选择,但有时由于某种原因我无法让它工作。您没有指定语言,所以这是 VB.NET 中的示例:

    Private Sub someTextField_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles someTextField.KeyPress
    
        If e.KeyChar.GetHashCode = 1769499 Then ''this number is the hash code for escape on my computer, do not know if it is the same for all computers though.
            MsgBox("escape pressed") ''put some logic in here that determines what ever you wanted to know about your "active control"
        End If
    
    End Sub
    

    【讨论】:

    • 感谢您的回复。我感兴趣的语言是C#。我正在寻找这个问题的通用解决方案。我不想为每个控件指定特定的代码。
    【解决方案3】:
    class Commands
    {
        static Command
        {
            CloseWindow = NewCommand("Close Window", "CloseWindow", new KeyGesture(Key.Escape));
            CloseWindowDefaultBinding = new CommandBinding(CloseWindow,
                CloseWindowExecute, CloseWindowCanExecute);
        }
    
        public static CommandBinding CloseWindowDefaultBinding { get; private set; }
        public static RoutedUICommand CloseWindow { get; private set; }
    
        static void CloseWindowCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = sender != null && sender is System.Windows.Window;
            e.Handled = true;
        }
        static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
        {
             ((System.Windows.Window)sender).Close();
        }
    }
    
    // In your window class's constructor. This could also be done
    // as a static resource in the window's XAML resources.
    CommandBindings.Add(Commands.CloseWindowDefaultBinding);
    

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 1970-01-01
      • 2010-11-11
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多