C# 检测Ctrl+c和其他程序退出

代码

using System;
using System.Threading;
public class Example
{
    public static void Main()
    {
        AppDomain appd = AppDomain.CurrentDomain;
        appd.ProcessExit += (s, e) =>
        {
            System.Console.WriteLine("Exit here.");
            Thread.Sleep(3000); // 停3秒
        };
        Console.CancelKeyPress += (sender, e) =>
        {
            e.Cancel = true; //true: 不导致退出。false: 会导致退出
            System.Console.WriteLine("You have Press Ctrl+C");
        };
        while(true)
        {
            System.Console.WriteLine("Go!");
            Thread.Sleep(1000);
        }
    }
}

上面这个控制台程序,启动后会每隔1秒输出"Go!"。
如果键盘键入"Ctrl + c",那么会进入Console.CancelKeyPress事件。
e.Cancel设置为true,会保持程序继续运行,如果设置成false,那么程序会直接退出,此时退出不会进入appd.ProcessExit事件代码。
如果点击控制台右上角×按钮关闭程序,则会进入appd.ProcessExit事件,我们能在程序退出前捕获到"Exit here”输出。

你可能感兴趣的:(c#)