Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Close a Window in WPF on a escape key

Tags:

c#

.net

wpf

xaml

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

I want to close the windows in my wpf project when the user clicks the escape button. I don't want to write the code in every window but want to create a class which can catch the when the user press the escape key.

like image 309
Kishore Kumar Avatar asked Oct 07 '11 19:10

Kishore Kumar


People also ask

How do I close a window in WPF?

Pressing ALT + F4 . Pressing the Close button.

Which property is used to exit close the form when pressed Esc?

Set the CancelButton property of the form to that button. Gets or sets the button control that is clicked when the user presses the Esc key. You will also have to set the KeyPreview property to true.

How do I close a page in WPF?

window. ShowDialog(); Close method of the Window class is used to close a window.


1 Answers

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(); } 
like image 171
CharithJ Avatar answered Sep 23 '22 18:09

CharithJ