首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在WPF窗口中处理"Esc“键?

如何在WPF窗口中处理"Esc“键?
EN

Stack Overflow用户
提问于 2010-04-19 10:18:16
回答 3查看 12.1K关注 0票数 5

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

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

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

如果你能用C#提供一个解决方案,那就太好了。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-04-20 05:43:40

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

票数 3
EN

Stack Overflow用户

发布于 2010-04-19 10:59:59

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

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2011-08-16 20:38:26

代码语言:javascript
运行
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2664884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档