How can I get my windows form to do something when it is closed.
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
.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With