How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

Viewed 21768

Is there any straightforward way of telling the whole WPF application to react to Escape key presses by attempting to close the currently focused widow? It is not a great bother to manually setup the command- and input bindings but I wonder if repeating this XAML in all windows is the most elegant approach?

<Window.CommandBindings>
        <CommandBinding Command="Close" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
        <KeyBinding Key="Escape" Command="Close" />
</Window.InputBindings>

Any constructive suggestions welcome!

8 Answers

create RoutedUICommand like below

 private static RoutedUICommand EscUICommand = new RoutedUICommand("EscBtnCommand"
       , "EscBtnCommand"
       , typeof(WindowName)
       , new InputGestureCollection(new InputGesture[] 
           { new KeyGesture(Key.Escape, ModifierKeys.None, "Close") }));

and add it command binding in constructor

CommandBindings.Add(new CommandBinding(EscUICommand, (sender, e) => { this.Hide(); }));

The Preview events happen quite early. If you have a control that should take the Esc key for its own purposes, stealing it at the window level may be too aggressive.

Instead you can handle it only if nothing else wants to:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);

    if (!e.Handled && e.Key == Key.Escape && Keyboard.Modifiers == ModifierKeys.None)
    {
        this.Close();
    }
}
Related