Capture console exit C#

前端 未结 10 2018
悲&欢浪女
悲&欢浪女 2020-11-22 04:01

I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termi

10条回答
  •  野性不改
    2020-11-22 05:02

    For those interested in VB.net. (I searched the internet and couldn't find an equivalent for it) Here it is translated into vb.net.

         _
        Private Function SetConsoleCtrlHandler(ByVal HandlerRoutine As HandlerDelegate, ByVal Add As Boolean) As Boolean
        End Function
        Private _handler As HandlerDelegate
        Private Delegate Function HandlerDelegate(ByVal dwControlType As ControlEventType) As Boolean
        Private Function ControlHandler(ByVal controlEvent As ControlEventType) As Boolean
            Select Case controlEvent
                Case ControlEventType.CtrlCEvent, ControlEventType.CtrlCloseEvent
                    Console.WriteLine("Closing...")
                    Return True
                Case ControlEventType.CtrlLogoffEvent, ControlEventType.CtrlBreakEvent, ControlEventType.CtrlShutdownEvent
                    Console.WriteLine("Shutdown Detected")
                    Return False
            End Select
        End Function
        Sub Main()
            Try
                _handler = New HandlerDelegate(AddressOf ControlHandler)
                SetConsoleCtrlHandler(_handler, True)
         .....
    End Sub
    

提交回复
热议问题