In a windows form project in C#/.net/Visual Studio 2010, if someone hits the close window button, I want to disable some other things in the program as a consequence. Is there a method call for hitting "X" that I can extend?
views:
80answers:
3
+1
Q:
Is there a way to have the close window button (X) call a method before actually closing the window?
Isn't the "FormClosed" event too late, after the form has already been closed?? You need "FormClosing" instead, I believe
marc_s
2010-08-01 07:45:50
Nothing in the question suggests that `FormClosing` would be needed over `FormClosed`. But I do admit that my answer is incomplete for not mentioning the second event, as other answers have.
jdmichal
2010-08-01 15:24:09
+6
A:
The two events that you should use are FormClosing
and FormClosed
.
In the .Net Framework verion 2.0 these events replaced the obsolete Closing
and Closed
events.
The reason for the new events was that the old ones were not raised when the Application.Exit
method was called.
An example of the usage of the FormClosing
event is below:
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Really close this form?", string.Empty, MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
That code simply asks the user if they want to close the form, and if No is selected, it then cancels the event. You can put any logic you require in the event handler.
The MSDN article on Form.Closing
is here and includes references about why the event was made obsolete. The reference for Form.FormClosing
is here
David Hall
2010-08-01 04:02:55