我希望按Esc键关闭我的WPF窗口。但是,如果有一个控件可以使用Esc键,我不想关闭窗口。在按Esc键时如何关闭WPF窗口有多种解决方案。例如:How does the WPF Button.IsCancel property work?
但是,此解决方案将关闭窗口,而不考虑是否存在可使用key键的活动控件。
例如。我有一个带DataGrid的窗户。dataGrid上的一列是组合框。如果我正在更改ComboBox,然后按Esc键,那么控件应该会从comboBox的编辑中出来(正常行为)。如果我现在再按一次Escape,那么窗口应该会关闭。我想要一个通用的解决方案,而不是编写大量的自定义代码。
如果你能用C#提供一个解决方案,那就太好了。
发布于 2010-04-20 05:43:40
您应该只使用KeyDown
事件,而不是PreviewKeyDown
事件。如果Window
的任何子级处理该事件,它将不会向上冒泡到窗口(从Window
向下的PreviewKeyDown
隧道),因此不会调用您的事件处理程序。
发布于 2010-04-19 10:59:59
可能有一种更简单的方法,但您可以使用散列代码来实现。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
发布于 2011-08-16 20:38:26
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);
https://stackoverflow.com/questions/2664884
复制相似问题