How to detect application close when no form is pr

2019-08-30 18:16发布

I've been wondering about this for a while.

I currently want an application to detect when it is being closed. The tricky thing is, this application is a console one meaning there is no form close event or like-wise.

I had a scout on google and really only came up with the code below which detects only shutting down, logging off and not specifically application closing.

ShutdownEvents Code:

Imports Microsoft.Win32
Module Module1

Sub Main()
    AddHandler (SystemEvents.SessionEnding), AddressOf ShutDown.OnShuttingdown
    AddHandler (SystemEvents.SessionEnded), AddressOf ShutDown.OnShutdown
    Console.ReadKey()
End Sub

Public Class ShutDown
    Public Shared Sub OnShuttingdown(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
        e.Cancel = True 'only set if you turn down the shutdown request
        Console.WriteLine("Shutting down - Reason is " & e.Reason)
        Console.ReadKey()
    End Sub

    Public Shared Sub OnShutdown(ByVal sender As Object, ByVal e As SessionEndedEventArgs)
        Console.WriteLine("Shutdown - Reason is " & e.Reason)
        Console.ReadKey()
    End Sub
End Class
End Module

Any help would be appreciated.

Regards,

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-30 18:27

You need to create a console control handler. There is no facility for doing that in the Console class, but you can call Windows API functions to do it. An example in C# is at Detecting Process Exit From Console Application in C#.

You'll want to read and understand the SetConsoleCtrlHandler API function.

I wrote a couple of articles a few years ago about using the Windows Console API from C#. Unfortunately, DevSource seems to have lost the one that describes this. The other two are available at

http://www.devsource.com/c/a/Using-VS/Working-with-Console-Screen-Buffers-in-NET/

and

http://www.devsource.com/c/a/Using-VS/Console-Input-in-NET/

Full source for the code presented in those articles is available at http://mischel.com/pubs/consoledotnet.zip.

查看更多
叛逆
3楼-- · 2019-08-30 18:42

Try an AddHandler for AppDomain.ProcessExit

e.g. via Thread.GetDomain

查看更多
登录 后发表回答