views:

262

answers:

4

Which event is fired when I close a form with the X button? I want the event that fires only when the X button is pressed; I know that there is a FormClosing event, but the problem is that it fires each time when form is closed... It also fires when frm.close() executes, and I don't want that to happen.

+5  A: 

There is no specific event wired up to the X in the upper right hand corner of the form.

Instead, use the form's FormClosing event. It has a Cancel parameter which you can set to false if you don't want the form to close. This allows you to check for form closings that take place via other means, such as the OK button being clicked.

Robert Harvey
thanks for quick answer
QueryUnload event is unheard of in WinForms.
Jacob Seleznev
+1  A: 

I use the form's OnClosing event, which can be cancelled as well.

SnOrfus
Obsolete in .NET Framework 2.0 and later. http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onclosing.aspx
Robert Harvey
+1  A: 

Hi! As Robert stated there is no specific event associated with 'X', but you basically have two options which can be used to solve your probelm.

(i) Form Closing - This event occurs when you click the 'X', but before closing the form. So you can use this event handler to do some stuff just before closing the form. For example, you can stop the form from being closed / destroyed by using e.Cancel();

(ii) Form Closed - This event occurs when the form is closed.

Regards

kobra
+4  A: 

You can check the CloseReason property of FormClosingEventArgs parameter. It is CloseReason.UserClosing when you click the 'X' button.

Jacob Seleznev