Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

button

exit

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

like image 930
adeena Avatar asked May 24 '09 18:05

adeena


People also ask

How do I close a form in Winforms?

Form. Close() is one method in closing a winform. When 'Form. Close()' execute , all resources created in that form are destroyed.

Which of the following method is used to close the windows form application?

Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.


2 Answers

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

like image 197
Peter C Avatar answered Nov 03 '22 23:11

Peter C


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;
}
like image 34
Matt Brindley Avatar answered Nov 04 '22 00:11

Matt Brindley