mohammed mohammed - 1 year ago 65 Question

i want to do something when i close console VB window is that possible?

I want to call function or execute some code when i

the window in console vb is that possible?

thanks in advance

Answer Source

Try this, I haven't tested it as such, i'll leave that up to you :) however this should lead you on the right direction :)

Module Module1
Public Enum ConsoleEvent
End Enum
Private Declare Function SetConsoleCtrlHandler Lib "kernel32" (ByVal handlerRoutine As ConsoleEventDelegate, ByVal add As Boolean) As Boolean
Public Delegate Function ConsoleEventDelegate(ByVal MyEvent As ConsoleEvent) As Boolean
Private handler As ConsoleEventDelegate

Sub Main()
    handler = AddressOf Application_ConsoleEvent
    If Not SetConsoleCtrlHandler(handler, True) Then
        Console.WriteLine("ERROR ADDING HANDLER")
        Console.WriteLine("Hello WORLD!")

    End If
End Sub
Public Function Application_ConsoleEvent(ByVal [event] As ConsoleEvent) As Boolean
    Dim cancel As Boolean = False
    Select Case [event]
        Case ConsoleEvent.CTRL_CLOSE_EVENT
            'ADD YOUR CLOSING CODE WITHIN HERE, you dont need to have the Msgbox, its just there so you can understand :)
            MsgBox("Program being closed!")
            ''ADD your clean up code if needed here.
    End Select

    Return cancel ' handling the event.
End Function
End Module

Let me know how you go :)

Happy Coding!