How to detect application close when no form is present (console application)

帅比萌擦擦* 提交于 2019-12-12 04:47:10

问题


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,


回答1:


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.




回答2:


Try an AddHandler for AppDomain.ProcessExit

e.g. via Thread.GetDomain



来源:https://stackoverflow.com/questions/16930457/how-to-detect-application-close-when-no-form-is-present-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!