.Net Or .Net Core C# 控制台捕获关闭事件的代码

Posted シ゛甜虾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.Net Or .Net Core C# 控制台捕获关闭事件的代码相关的知识,希望对你有一定的参考价值。

/*
1:通过点击控制台的关闭按钮
2:按Ctrl+C,强制性关闭控制台
*/
using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Runtime.InteropServices;  
using System.Threading;  
  
namespace ConsoleClose  
{  
    public delegate bool ControlCtrlDelegate(int CtrlType);  
    class Program  
    {  
        [DllImport("kernel32.dll")]  
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);  
  
        static ControlCtrlDelegate newDelegate = new ControlCtrlDelegate(HandlerRoutine);  
  
        public static bool HandlerRoutine(int CtrlType)  
        {  
            switch (CtrlType)  
            {  
                case 0:   
                    Console.WriteLine("0程序被Ctrl+C关闭!"); //Ctrl+C关闭  
                    //相关代码执行

                    break;  
                case 2:  
                    Console.WriteLine("2程序被控制台关闭按钮关闭");//按控制台关闭按钮关闭 
                    //相关代码执行 

                    break;  
            }  
            return false;  
        }  
  
        static void Main(string[] args)  
        {  
            bool bRet = SetConsoleCtrlHandler(newDelegate, true);  
  
            //这后面写程序该做的事情  
            while(true)  
            {  
                Console.WriteLine("程序运行中!");  
                Thread.Sleep(5000);  
            }  
        }  
    }  
}  

以上是关于.Net Or .Net Core C# 控制台捕获关闭事件的代码的主要内容,如果未能解决你的问题,请参考以下文章