Visual Basic 6 – How to clean Shutdown an application (ExitProcess)

Send Us a Sign! (Contact Us!)
--> (Word) --> (PDF) --> (Epub) --> (Text)
--> (XML) --> (OpenOffice) --> (XPS) --> (MHT)

SCENARIO

I can shut this program down and it may remain in the running programs list that you get with "Ctrl-Alt-Del" for 2 or 3 minutes or more.

SOME INFO

[tab:End]

About END statement:

END close the program immediately, destroying variable, but not OBJECT REFERENCE, if you have any object that reference to whatever, make sure you use SET objObject = nothing.

Also, the END don't call the QueryUnload event and the Unload event, make sure you Unload formName each form of your projects.

Make sure each class and .dll are destroyed by you, the END statement will not do it.

[tab:ExitProcess]

About ExitProcess statement:

From Microsoft MSDN: ExitProcess is the preferred method of ending a process. This function provides a clean process shutdown. This includes calling the entry-point function of all attached dynamic-link libraries (DLLs) with a value indicating that the process is detaching from the DLL. If a process terminates by calling TerminateProcess, the DLLs that the process is attached to are not notified of the process termination.

[tab:END]

SOLUTION

Create a button in your project and assign it the following code (the Private Declare Sub … must go under Declarations section in your project!):

Private Declare Sub ExitProcess Lib "kernel32" (ByVal uExitCode As Long)
Private Sub Command1_Click()
ExitProcess 0
End Sub

SOLUTION 2

If you’re trying your application within VB6 IDE you will notice that the ExitProcess 0 will also terminate your VB6 IDE main application (Visual Basic 6 Editor), even it is in Debug mode. To “fix” this issue you will have to declare two simple constants to tell your application how it will terminate:

Option Explicit
Private Const MODE_DEV = 0
Private Const MODE_EXE = 1
'You just need to change this value when compiling your EXE
Private Const mode = MODE_DEV
'Private Const mode = MODE_EXE
Private Declare Sub ExitProcess Lib "kernel32" (ByVal uExitCode As Long)
Private Sub Command1_Click()
If mode = MODE_DEV Then
End
ElseIf mode = MODE_EXE Then
ExitProcess 0
End If
End Sub

Of course, it means you will not be using ExitProcess in debug mode. If your program don't terminate normally, you you can use VB to stop your application in developement mode and when you compile, by changing the value of the variable, you will have an EXE that end with the ExitProcess API.

SOURCE

LINK (codeguru.com)

LANGUAGE
ENGLISH