How do I go about overriding the default functionality when a user clicks the X in a VB.NET form-based application?
I am currently handling the MyBase.Closing event.
If you don't feel comfortable putting your code in the Form_Closing event, the only other option I am aware of is a "hack" that I've used once or twice. It should not be necessary to resort to this hack, but here it is:
Don't use the normal close button. Instead, create your form so that it has no ControlBox. You can do this by setting ControlBox = false on the form, in which case, you will still have the normal bar across the top of the form, or you can set the form's FormBorderStyle to "None. If you go this second route, there will be no bar across the top, or any other visible border, so you'll have to simulate those either by drawing on the form, or by artistic use of Panel controls.
Then you can add a standard button and make it look like a close button, and put your clean-up code in there. At the end of the button event, just call this.Close()
(C#) or Me.Close()
(VB)
Re your other comments; doing anything before the event has fired would be premature; after all, some other code might cancel the close, and you'd be left with a scuppered form. Personally, I'd be tempted to override OnClosed
; not much of a VB head, but in C#:
protected override void OnClosing(CancelEventArgs e)
{
// check OK to close (save/cancel etc)
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
// your code here
base.OnClosed(e);
// or here
}
If you want to do some extra clean up before a form closes, do so in the form's Form Closing event.
This event also allows you to cancel the form close through the event's FormClosingEventArgs.Cancel property. The event's CloseReason property will tell you why the event was called (you'd check for CloseReason.UserClosing)