views:

311

answers:

3

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... but since it's a DirectX app, I need to do some cleanup before allowing the form the close.

Thanks

+2  A: 

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)

Jay Riggs
This is not an option for this application. I need to do some cleanup when the user clicks X and this cleanup cannot be initiated from the Closing Event. My question relates to overriding the functionality of the X button.
hamlin11
The form doesn't have to close when the Form Closing event fires. You can cancel it. That wouldn't suit your needs?
Jay Riggs
That wouldn't not suit my needs
hamlin11
Well, that's not not good.
Jay Riggs
@Jay Riggs: -1*(-1) for the smart double negation answer :)
johnnyArt
+1  A: 

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)

David Stratton
+1  A: 

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
    }
Marc Gravell