How is the Esc key handled in a WPF window?

I want the Escape key to close the WPF window. However, if there is a control that can use this Escape key, I do not want to close the window. There are several solutions on how to close the WPF window when you press the ESC key. eg. How does the WPF Button.IsCancel property work?

However, this solution closes the window, regardless of whether there is an active control that can use the Escape key.

For example, I have a window with a DataGrid. One of the columns in the dataGrid is a combobox. If I change the ComboBox and hit Escape, then the control should exit comboBox (Normal Behavior) editing. And if I remove Escape again, the Window should close. I would like to get a general solution instead of writing a lot of custom code.

If you can provide a solution in C #, that would be great.

+5
source share
3 answers

You should just use an event KeyDowninstead of an event PreviewKeyDown. If any child Windowhandles the event, it will not bubble up to the window ( PreviewKeyDowntunnels from Windowdown), and therefore your event handler will not be called.

+3

, -. 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
+1
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 constructor. This could also be done
// as a static resource in the window XAML resources.
CommandBindings.Add(Commands.CloseWindowDefaultBinding);
+1
source

All Articles