控制台应用,在运行阶段很有可能被用户Ctrl+C终止或是被用户直接关闭。
在关闭时希望执行一段处理逻辑
Windows API中有个SetConsoleCtrlHandler函数可以处理Ctrl+C和直接关闭控制台应用这两种关闭事件
命名空间
using System.Runtime.InteropServices;
public delegate bool ConsoleShutdownDelegate(int CtrlType);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleShutdownDelegate HandlerRoutine, bool Add);
private static readonly ConsoleShutdownDelegate cancelHandler = new(HandlerShutdown);
static void Main(string[] args)
{
SetConsoleCtrlHandler(cancelHandler, true);
Console.ReadLine();
}
public static bool HandlerShutdown(int CtrlType)
{
Console.WriteLine("退出时处理逻辑...");
switch (CtrlType)
{
case 0:
Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭
break;
case 2:
Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭
break;
}
Console.ReadLine();
return false;
}