How to Close Console Application Gracefully on Windows Shutdown

后端 未结 3 922
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 22:50

I am trying to close my vb.net console app gracefully when windows shutdown occurs. I have found examples that call the Win32 function SetConsoleCtrlHandler that all basically

3条回答
  •  心在旅途
    2021-01-20 23:38

        If Not SetConsoleCtrlHandler(AddressOf Application_ConsoleEvent, True) Then
    

    This is the statement that gets you into trouble. It creates a delegate instance on-the-fly and passes it to unmanaged code. But the garbage collector cannot see the reference held by that unmanaged code. You'll need to store it yourself so it won't be garbage collected. Make that look like this:

    Private handler As ConsoleEventDelegate
    
    Sub Main()
        handler = AddressOf Application_ConsoleEvent
        If Not SetConsoleCtrlHandler(handler, True) Then
           '' etc...
    

    The handler variable now keeps it referenced and does so for the life of the program since it is declared in a Module.

    You cannot cancel a shutdown btw, but that's another issue.

提交回复
热议问题