How to know whether window was closed by “x” butto

2019-04-22 01:02发布

问题:

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

回答1:

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.



回答2:

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



标签: wpf window