C#控制台关闭时回调操作处理其他操作,这时候需要用到Windows api的,
功能:向系统添加或删除回调函数。
说明:利用它可以设置回调函数,当控制台窗口发生事件时,事件首先发送给回调函数,你可以在回调函数中对事件处理。
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(delegate callback, bool add);//callback 委托,add 添加或者删除,true 添加,false 删除
代码如下:
using ServiceX;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace ServiceXConsole
{
class Program
{
//static Logger<Program> logger = new Logger<Program>();
#region kernel32
//定义委托
private delegate bool ConsoleEventDelegate(int eventType);
//winApi---控制台关闭回调接口
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
//volatile static 变量防止优化
volatile static ConsoleEventDelegate consoleCtrlDelegate = new ConsoleEventDelegate(HandlerRoutine);
#endregion
static void Main(string[] args)
{
try
{
bool isSuccess = SetConsoleCtrlHandler(consoleCtrlDelegate, true);
Thread.CurrentThread.IsBackground = false;
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
// logger.Error("Main", e);
}
}
/// <summary>
/// Console控制台关闭时回调操作释放资源
/// </summary>
/// <param name="CtrlType"></param>
/// <returns></returns>
public static bool HandlerRoutine(int CtrlType)
{
switch (CtrlType)
{
case 0:
//相关代码
break;
case 2:
//Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭
List<Process> pList = Process.GetProcessesByName("adb").ToList();
try
{
string processFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "adb.exe");
pList.ForEach(proc =>
{
if (proc.ProcessName == "adb" && proc.MainModule.FileName == processFilePath)
{
proc.Kill();
proc.WaitForExit();
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
break;
}
return false;
}
}
}