Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know whether window was closed by "x" button?

Tags:

window

wpf

Does anyone knows how to find out whether wpf window was closed by "x" button?

like image 972
vts123 Avatar asked Dec 08 '09 12:12

vts123


2 Answers

The simplest way (in my opinion) is to store a boolean indicating if a user has closed the form via another method(s).

Then in the OnClosing event, do a check to see if the boolean is false (indicating that the x button was clicked).

The only issue with this is the fact you have set the boolean youself. Wether this is possible is dependant on the other way the user could close your form.

EDIT: I should point out that this is highly dependant on the other ways the form can be closed. If you have a number of methods that close this window by calling Window.Close(), i would consider creating a single method called UserClose(), which does the boolean setting for you.

public void UserClose()
{
    NonXClose = true;
    this.Close();
}

This will allow outside code to close the window, with the setting of the boolean.

like image 171
Alastair Pitts Avatar answered Oct 25 '22 23:10

Alastair Pitts


The difference is the following:

Window.Close() causes WM_CLOSE to be send to window.

Alt+F4 and X button causes WM_SYSCOMMAND message with SC_CLOSE type. You can decide if you wish to route this message further ( and cause WM_CLOSE in the end ).

Look for my answer with code example here

like image 42
norekhov Avatar answered Oct 26 '22 00:10

norekhov