If you are not comfortable adding your code to the Form_Closing event, the only other option that I know of is a “hack”, which I used once or twice. No need to resort to this hacking, but here it is:
Do not use the normal close button. Instead, create your form so that it does not have a ControlBox. You can do this by setting ControlBox = false on the form, in which case you will still have a normal bar at the top of the form, or you can set the FormBorderStyle form to "None". If you follow this second route, there will not be a single bar at the top or any other visible border, so you will have to simulate them either by drawing a form or by using the Panel controls artfully.
Then you can add a standard button and make it look like a close button and put the cleanup code there. At the end of the button event, just call this.Close() (C #) or Me.Close() (VB)
David Oct 13 '09 at 20:57 2009-10-13 20:57
source share