How is "Esc" key handled in WPF Window?
I want the Escape key to close my WPF window. However if there is a control that can consume that Escape key, I don't want to close the Window. There are multiple solutions on how to close the WPF Window when ESC key is pressed. eg. How does the WPF Button.IsCancel property work?
However this solution closes the Window, without regard to if there is an active control that can consume the Escape key.
For eg. I have a Window with a开发者_如何学运维 DataGrid. One of the columns on the dataGrid is a combobox. If I am changing the ComboBox, and hit Escape, then the control should come out of editing of the comboBox (Normal Behavior). And if I now hit Escape again, then the Window should close. I would like a generic solution, instead of writing a lot of custom code.
If you can provide a solution in C# it would be great.
You should just use the KeyDown
event instead of the PreviewKeyDown
event. If any child of the Window
handles the event, it won't be bubbled up to the Window (PreviewKeyDown
tunnels from the Window
down), and therefore your event handler won't be called.
There may be an easier way, but you could do it with the hash code. Keys.Escape is another option, but sometimes I cannot get that to work for some reason. You didn't specify a language so here is an example in 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
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);
精彩评论