tags:

views:

79

answers:

6

In Visual C#, how can I detect if the user clicks the X button to close the program? I want to ask the user if they'd like to perform a certain action before exiting. I have an exit button in my program itself, and I know I can code it as follows:

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DialogResult result;
        if (logfiletextbox.Text != "")
        {
            result = MessageBox.Show("Would you like to save the current logfile?", "Save?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
            if (result == DialogResult.Yes)
            {
                savelog.PerformClick();
            }
        }
        Environment.Exit(0); //exit program
    }

But how can I do this for the X button that is already built into the program?

+4  A: 

Add an event handler for FormClosing on the form.

The Form designer will do this for you automatically if you select the event, but to do it manually:

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);

And then add the handler into your code:

private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
  //Code here
}

If you don't want to close the form then you can set: e.Cancel = true;

Brian R. Bondy
A: 

If you're using a form, you can catch the Form.FormClosing event. It can be cancelled by setting the Cancel property in the args, based on user input.

Mau
You should use the newer `Form.FormClosing` event instead.
SLaks
Thanks. Updated the answer :-)
Mau
+2  A: 

There is a FormClosing event you can bind to that gets fired when the form is about to close. The event handler includes a link to the reason the form is closing (user action, OS shutdown, etc), and offers you an option to cancel it.

Check out the MSDN article here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx

rakuo15
+2  A: 

use the Application.Exit or Form.Closing event. Exit won't let you cancel, so Closing is probably a better choice

Jason
The Closing event is deprecated in favor of the FormClosing event.
R. Bemrose
+2  A: 
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("cancel?", "a good question", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            e.Cancel = true;
        }
    }

It's the "FormClosing" - event of the form. Have fun, friend.

Turing Complete
A: 

Just use FormClosing event of form

Nakul Chaudhary