您的位置:首页 > 编程语言 > C#

C#杀死手动关闭控制台程序,遗留的进程

2016-06-01 14:14 465 查看
先贴.cs文件,再写调用方法:

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Linq;

using System.Text;

using System.Runtime.InteropServices;

namespace VMAIMComputingNode

{

    class ConsolControl

    {

        private delegate bool ConsoleCtrlDelegate(int dwCtrlType);

        const int CTRL_CLOSE_EVENT = 2;//关闭控制台事件

  

        ConsoleCtrlDelegate newDelegate = new ConsoleCtrlDelegate(HandlerRoutine);

     

        [DllImport("kernel32.dll")]

        private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);

        public bool KillCameraPro()

        {

            if (!SetConsoleCtrlHandler(newDelegate, true))

            {

                Console.WriteLine("API注入失败,不能自动关闭camera进程");

                return false;

            }

            return true;

        }

        static bool HandlerRoutine(int CtrlType)

        {

            switch (CtrlType)

            {

                case CTRL_CLOSE_EVENT:       //用户要关闭Console了

                                             // Console.WriteLine();

                    Process[] p = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("CameraData.exe"));

                    foreach (Process pp in p)

                    {

                        pp.Kill();

                    }

                    Console.WriteLine("任务还没有完成,确认要退出吗?(Y/N)");

                    ConsoleKeyInfo ki = Console.ReadKey();

                    return ki.Key == ConsoleKey.Y;

                default:

                    return true;

            }

        }

    }

}

调用方法:

前提,同一命名空间中

 ConsolControl cc = new ConsolControl();

           bool resullt= cc.KillCameraPro();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息