开发者

"On Exit" for a Console Application [duplicate]

This question already has answers here: 开发者_Python百科 Capture console exit C# (10 answers) Closed 8 years ago.

I am looking for a way to trigger a piece of code when a console application is manually closed (users closes window). Been trying with:

AppDomain.CurrentDomain.ProcessExit +=
    new EventHandler(CurrentDomain_ProcessExit);

but the above doesn't work if manually closed.

Is there any ways to use a .Net call for this or do I need to import the Kernel dll and do it that way?


This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().


You need to hook to console exit event and not your process.

http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx

Capture console exit C#

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜