您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#如何結束進程及子進程”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#如何結束進程及子進程”吧!
代碼如下:
static class ProcessExtend { // [StructLayout(LayoutKind.Sequential)] private struct ProcessBasicInformation { public int ExitStatus; public int PebBaseAddress; public int AffinityMask; public int BasePriority; public uint UniqueProcessId; public uint InheritedFromUniqueProcessId; } [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess( IntPtr hProcess, int processInformationClass /* 0 */, ref ProcessBasicInformation processBasicInformation, uint processInformationLength, out uint returnLength ); public static void KillProcessTree(this Process parent) { var processes = Process.GetProcesses(); foreach (var p in processes) { var pbi = new ProcessBasicInformation(); try { uint bytesWritten; if (NtQueryInformationProcess(p.Handle, 0, ref pbi, (uint)Marshal.SizeOf(pbi), out bytesWritten) == 0) // == 0 is OK if (pbi.InheritedFromUniqueProcessId == parent.Id) using (var newParent = Process.GetProcessById((int)pbi.UniqueProcessId)) newParent.KillProcessTree(); } catch { } } parent.Kill(); } }
PS:今天發現NtQueryInformationProcess函數在x64位程序上運行無效, 具體原因不明,Google了一下也沒有找到答案,反而找到了另一種解決方案,通過WMI來實現的。在x86和x64下都可以使用。
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 */ } }
感謝各位的閱讀,以上就是“C#如何結束進程及子進程”的內容了,經過本文的學習后,相信大家對C#如何結束進程及子進程這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。