C#控制台关闭时回调操作处理其他操作

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;
        }
    }
}
复制代码

 

posted @   龙骑科技  阅读(156)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2020-04-13 Nginx配置upstream实现负载均衡
2020-04-13 nlog在.NET Core项目中使用案例
2020-04-13 log4net在.NET Core项目中使用案例
2016-04-13 异常:System.BadImageFormatException,未能加载正确的程序集XXX
点击右上角即可分享
微信分享提示