static class Program
{
public delegate bool ControlCtrlDelegate(int CtrlType);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);
public static bool HandlerRoutine(int CtrlType)
{
switch (CtrlType)
{
case 0:
Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭
break;
case 2:
Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭
break;
}
Console.ReadLine();
return false;
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
SetConsoleCtrlHandler(cancelHandler, true);
Console.ReadLine();
}
}