vts123
vts123

Reputation: 1776

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

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

Upvotes: 9

Views: 5534

Answers (2)

norekhov
norekhov

Reputation: 4233

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

Upvotes: 3

Alastair Pitts
Alastair Pitts

Reputation: 19591

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.

Upvotes: 12

Related Questions