一尘不染

如何以托管方式在.NET中获取父进程

c#

我一直在寻找在.NET中获取父进程的方法,但只找到了P / Invoke方式。


阅读 273

收藏
2020-05-19

共1个答案

一尘不染

这段代码提供了一个不错的接口来查找父流程对象,并考虑了多个具有相同名称的流程的可能性:

用法:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);

码:

public static class ProcessExtensions {
    private static string FindIndexedProcessName(int pid) {
        var processName = Process.GetProcessById(pid).ProcessName;
        var processesByName = Process.GetProcessesByName(processName);
        string processIndexdName = null;

        for (var index = 0; index < processesByName.Length; index++) {
            processIndexdName = index == 0 ? processName : processName + "#" + index;
            var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
            if ((int) processId.NextValue() == pid) {
                return processIndexdName;
            }
        }

        return processIndexdName;
    }

    private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
        var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
        return Process.GetProcessById((int) parentId.NextValue());
    }

    public static Process Parent(this Process process) {
        return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
    }
}
2020-05-19