C#控制台关闭之前做一些操作

2021-04-27 03:27

阅读:672

标签:imp   garbage   dea   error   stat   shu   rgs   控制   service   

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);
}

参考资料:
https://stackoverflow.com/questions/4646827/on-exit-for-a-console-application

C#控制台关闭之前做一些操作

标签:imp   garbage   dea   error   stat   shu   rgs   控制   service   

原文地址:http://www.cnblogs.com/Lulus/p/7872261.html


评论


亲,登录后才可以留言!