参考:如何杀死进程及子进程
/** * 传入参数:父进程id * 功能:根据父进程id,杀死与之相关的进程树 */ public static void KillProcessAndChildren(int pid) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection moc = searcher.Get(); foreach (ManagementObject mo in moc) { KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"])); } try { Process proc = Process.GetProcessById(pid); Console.WriteLine(pid); proc.Kill(); } catch (ArgumentException) { /* process already exited */ } }
常用的Process方法:
//1.根据进程id,获得进程 Process p = Process.GetProcessById(100); //2.获取当前进程 Process p = Process.GetCurrentProcess(); //3.根据进程名字获取进程,返回的结果是一个数组 Process p = (Process.GetProcessesByName("DriverEasy"))[0];
特别声明:因为代码中使用到了 ManagementObjectSearcher,如果在Visual Studio中即使引入了
命名空间,还是提示无法找到相应的类的话,那么按下面说的来做,
第一步:在项目上鼠标右键 -> add -> Reference
第二步:找到 System.Management,把它前面的勾打上
OK了
时间: 2024-11-07 10:03:10