9

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
vts123
  • 1,736
  • 6
  • 27
  • 41
  • Can you clarify? Do you want to distinguish between pressing the "X" button and other means of closing the window (i.e. keyboard)? Or any means of closing the window? – R. Martinho Fernandes Dec 08 '09 at 12:06
  • distinguish between pressing the "X" button and other means of closing the window (i.e. keyboard) – vts123 Dec 08 '09 at 13:26
  • 1
    I think it would be helpful if you explain why you want to do this. To the user, it shouldn't matter whether its closed by the X or a menu item. Maybe then we can help you achieve what you really want to do instead – Isak Savo Dec 08 '09 at 14:50

2 Answers2

12

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.

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
3

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

Community
  • 1
  • 1
norekhov
  • 3,915
  • 25
  • 45