Kuzon
Kuzon

Reputation: 822

How to run code on Exit vb.net

I would just like to know how to run code in vb.net when the program is closed with the red cross in the top right of the screen.

Upvotes: 0

Views: 4076

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18280

Use Form.FormClosing Event - Read the Remarks on this event documentation for better implementation of your functionality.

It occurs before the form is closed.

Check FormClosingEventArgs properties for further manipulations:

e.CloseReason

e.Close

However, canceling the event will set to true the Cancel property of the FormClosingEventArgs class that is passed as a parameter to the parent form. To force all MDI parent and child forms to close, set the Cancel property to false in the MDI parent form.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            sr.WriteLine("8 - FormClosing");
        }

Windows Forms Events Lifecycle

Upvotes: 1

stuartd
stuartd

Reputation: 73313

You need to handle the FormClosing event: use the CloseReason property of the FormClosingEventArgs to determine why the form is closing - you want to look for CloseReason.UserClosing - and set the Cancel property to true if you want to cancel the form close.

Upvotes: 1

Related Questions