static int VAR_ProcessIdOfIpeCmd = 0; private void Task_StopFirmwareFlashing() { // 刪除所紀錄的Process與其Child Process RecursiveTask_KillProcessAndChildren(VAR_ProcessIdOfIpeCmd); } private void Task_StopFirmwareFlashing() { // 刪除所紀錄的Process與其Child Process RecursiveTask_KillProcessAndChildren(VAR_ProcessIdOfIpeCmd); } private static void RecursiveTask_KillProcessAndChildren(int pid) { // 這是一個遞迴的程序,會針對所有以傳入之pid為parent Process // 的Process,再重複遞迴找尋,直到所有最終沒有任何Procee以其為parent // 的Process, 將之進行關閉 Process // ------------------------------------- // 無法刪除(關閉) 'system idle process' if (pid == 0) { return; } // 找尋所有之Child Process ManagementObjectSearcher searcher = new ManagementObjectSearcher ("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection moc = searcher.Get(); // 對每一個Child Process 再遞迴方式找尋一次 foreach (ManagementObject mo in moc) { RecursiveTask_KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"])); } // 沒有Child Process時,嘗試刪除該Process try { Process proc = Process.GetProcessById(pid); proc.Kill(); } catch (ArgumentException) { // Process already exited. } }