How to Close a Window in WPF on a escape key

Option 1

Use Button.IsCancel property.

<Button Name="btnCancel" IsCancel="true" Click="OnClickCancel">Cancel</Button>

When you set the IsCancel property of a button to true, you create a
Button that is registered with the AccessKeyManager. The button is
then activated when a user presses the ESC key.

However, this works properly only for Dialogs.

Option2

You add a handler to PreviewKeyDown on the window if you want to close windows on Esc press.

public MainWindow()
{
    InitializeComponent();

    this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
}

private void HandleEsc(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Escape)
        Close();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)