C#中如何获取父进程ID
在C#中,可以使用System.Diagnostics
命名空间来获取父进程的ID。下面是一个示例代码:
using System; using System.Diagnostics; class Program { static void Main() { int parentId = GetParentProcessId(); Console.WriteLine("Parent Process ID: " + parentId); } static int GetParentProcessId() { int parentId = -1; try { Process currentProcess = Process.GetCurrentProcess(); parentId = currentProcess.Parent().Id; } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } return parentId; } } public static class ProcessExtensions { public static Process Parent(this Process process) { try { using (ManagementObject managementObject = new ManagementObject($"win32_process.handle='{process.Id}'")) { managementObject.Get(); int parentId = Convert.ToInt32(managementObject["ParentProcessId"]); return Process.GetProcessById(parentId); } } catch { return null; } } }
这个例子中,GetParentProcessId
方法使用System.Management
命名空间获取当前进程的父进程ID。注意需要引用System.Management
程序集。