How do I add code to the exit button in a c# form?

19,553

Solution 1

Using the FormClosing Event should catch any way of closing the form.

Solution 2

In the Design view for your form, within the Properties window, select the Events button and scroll down to the "FormClosed" and "FormClosing" events.

FormClosed is called after the form is closed.

FormClosing is called before the form is closed and also allows you to cancel the close, keeping the form open:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
}

Solution 3

If you want to ask the user "Are you sure you want do close this form?", then use FormClosing, where you can set Cancel = True and the form would remain open.

If you want to close some resource only when the form is definitely closed, then you use FormClosed event.

If you are in control of the whole code, then it kind of does not matter. But what you do not want to happen is to clean-up the resources using FormClosing when the the other handler of the event will keep the form open.

Share:
19,553
adeena
Author by

adeena

I'm an Software/Systems Engineer, Author, Speaker, and all around geek. https://adeenamignogna.com

Updated on June 04, 2022

Comments

  • adeena
    adeena almost 2 years

    I'm using Microsoft Visual C# 2008 Express.

    In my main form, there's that X button to close the form at the top right. How do I add code to this button? In my menu, I have an "Exit" item and it has code that cleans up and closes my databases. How do I add the same code to this button if the user chooses that as a way to exit?

    Thanks!

    -Adeena

  • adeena
    adeena about 15 years
    is that "FormClosed" or "FormClosing"? or does it not matter if all I'm doing is things like closing databases...?
  • KtorZ
    KtorZ about 15 years
    Sorry, typo: I meant the Closed-Event. But I just read that it is replaced by the FormClosed-Event from .NET 2.0 updwards