Before Application Exit


Well-known member
Jun 3, 2004
Programming Experience
Hi, is there a way that i can run some code before the application exits? So that when the last form is closed, or the exit button is clicked, it runs a short piece of code before closing itself? The problem is that there is no way to know what form will be that last open, so can i put some code into a module or something?
In VB.NET with Version 1.X framework, if you use a form as the startup object, the application exits when that form is closed (all other forms are closed as well). I say in version 1.X because version 2 (VB8) gives you the choice of ending the app when the startup form is closed or after all forms are closed. In version 2 there is also a special place to put code that you want executed before the app ends (in the MyApplication class' ShutDown event handler).

Back to Vb7: you could use a Sub Main procedure in a module or class to start the application in which case you would open the main form as a modal form and put the code you want executed after that call.
Thanks for the reply. It works well. I have it load my main form. But if i then load another form from the main form, and hide the main form, it closes the app?
I'm using the following on my startup Module.
[size=2][/size][size=2][color=#0000ff]Sub[/color][/size][size=2] Main()[/size]
[size=2][color=#0000ff]Dim[/color][/size][size=2] MainForm [/size][size=2][color=#0000ff]As[/color][/size][size=2] [/size][size=2][color=#0000ff]New[/color][/size][size=2] frmMain[/size]
[size=2][color=#0000ff]End[/color][/size][size=2] [/size][size=2][color=#0000ff]Sub[/color][/size]
Is this alright? How can i stop the app from closing when the Mainform loses focus?
Last edited: