【问题标题】:How to detect application close when no form is present (console application)没有表单时如何检测应用程序关闭(控制台应用程序)
【发布时间】:2013-06-05 02:10:22
【问题描述】:

我一直在想这个问题。

我目前希望应用程序检测它何时被关闭。棘手的是,这个应用程序是一个控制台,这意味着没有表单关闭事件或类似事件。

我在谷歌上有一个侦察员,真的只想出了下面的代码,它只检测到关闭、注销而不是具体的应用程序关闭。

关机事件代码:

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

任何帮助将不胜感激。

问候,

【问题讨论】:

    标签: .net vb.net forms windows-7


    【解决方案1】:

    您需要创建一个控制台控制处理程序。在Console 类中没有执行此操作的工具,但您可以调用 Windows API 函数来执行此操作。 C# 中的一个示例位于Detecting Process Exit From Console Application in C#

    您需要阅读和理解SetConsoleCtrlHandler API 函数。

    几年前,我写了几篇关于在 C# 中使用 Windows 控制台 API 的文章。不幸的是,DevSource 似乎失去了描述这一点的那个。其他两个可在

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

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

    这些文章中提供的代码的完整源代码可在 http://mischel.com/pubs/consoledotnet.zip 获得。

    【讨论】:

    • 感谢您的提示,但我真的不打算为这个应用程序深入研究 winapi。
    【解决方案2】:

    尝试为AppDomain.ProcessExit 使用 AddHandler

    例如通过Thread.GetDomain

    【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    相关资源
    最近更新 更多