Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Windows Form: On Close Do [Process]

Tags:

How can I get my windows form to do something when it is closed.

like image 389
sooprise Avatar asked May 25 '10 15:05

sooprise


2 Answers

Handle the FormClosed event.

To do that, go to the Events tab in the Properties window and double-click the FormClosed event to add a handler for it.

You can then put your code in the generated MyForm_FormClosed handler.

You can also so this by overriding the OnFormClosed method; to do that, type override onformcl in the code window and OnFormClosed from IntelliSense.

If you want to be able to prevent the form from closing, handle the FormClosing event instead, and set e.Cancel to true.

like image 108
SLaks Avatar answered Sep 25 '22 01:09

SLaks


Or another alternative is to override the OnFormClosed() or OnFormClosing() methods from System.Windows.Forms.Form.

Whether you should use this method depends on the context of the problem, and is more usable when the form will be sub classed several times and they all need to perform the same code.

Events are more useful for one or two instances if you're doing the same thing.

public class FormClass : Form {    protected override void OnFormClosing(FormClosingEventArgs e)    {         base.OnFormClosing(e);         // Code    }  } 
like image 26
Ian Avatar answered Sep 25 '22 01:09

Ian