views:

80

answers:

3

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?

A: 

Just register a handler on the FormClosed event.

jdmichal
Isn't the "FormClosed" event too late, after the form has already been closed?? You need "FormClosing" instead, I believe
marc_s
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
+1  A: 

Your window class publishes two events for this purpose:

Closing allows you to cancel the close if it's inappropriate

Closed allows you to react on close.

Bevan
+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
Cool!! I was pretty sure there was something easy like that.Thanks!!
SDGator