Search code examples
vb.netexithandlecommand-line-interface

Execute a subroutine before exiting the application


I am designing a client-server application, where the client requests various data and the server retrieves it from the local SQL server.

I need to execute a function when the application exits in order to tell associated services that the server is offline, but I am unable to figure out exactly how to do this.

This related question seems to have the answer:

handle the AppDomain.ProcessExit event, which is raised when the application's parent process exits.

however when using the below code the onExit subroutine does not get executed on application closure, probably because I am using the wrong approach to this problem or that Environment.Exit isn't executed when the application exits:

    Dim myConn As SqlConnection
    Dim cmd As New SqlCommand

    Sub Main()
        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf onExit 
    End Sub

    Public Sub onExit(sender As Object, e As EventArgs)
        'Unrelated code removed here.
    End Sub

To clarify, I need it to execute onExit when the user closes the application; I am not looking to close the application via a console command.

I've also thought that perhaps I could add a Handle to onExit but I have no idea what to use here.

Is it possible to reliably execute a subroutine or function when the user attempts to close the application via the standard Windows Explorer user interface? This is a console application, I know this can be very easily done in Windows Forms and thought it would be easy in console. Obviously not.


Solution

  • You need to import the SetConsoleCtrlHandler like in this sample:

    Module Module1
        Public Declare Function SetConsoleCtrlHandler Lib "kernel32" (Handler As ConsoleCtrlDelegate, Add As Boolean) As Boolean
        Public Delegate Sub ConsoleCtrlDelegate()
        Sub Main()
            SetConsoleCtrlHandler(New ConsoleCtrlDelegate(AddressOf OnExit), True)
            Console.WriteLine("Please try to close down...")
            Console.ReadLine()
        End Sub
    
        Sub OnExit()
            MsgBox("Help I'm being closed!")
        End Sub
    End Module