我怎样才能让我的应用程序的父进程的PID我的、应用程序、进程、PID

2023-09-02 01:22:46 作者:看到这昵称的都是美妞

我的WinForm应用程序由另一个应用程序(父),我需要确定应用程序的PID至极使用C#启动我的应用程序,启动

My winform application is launched by another application (the parent), i need determine the pid of the application wich launch my application using c#.

推荐答案

WMI是更简单的方式来做到这一点在C#。 Win32_Process类有ParentProcessId财产。这里有一个例子:

WMI is the easier way to do this in C#. The Win32_Process class has the ParentProcessId property. Here's an example:

using System;
using System.Management;  // <=== Add Reference required!!
using System.Diagnostics;

class Program {
    public static void Main() {
        var myId = Process.GetCurrentProcess().Id;
        var query = string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
        var search = new ManagementObjectSearcher("root\CIMV2", query);
        var results = search.Get().GetEnumerator();
        results.MoveNext();
        var queryObj = results.Current;
        var parentId = (uint)queryObj["ParentProcessId"];
        var parent = Process.GetProcessById((int)parentId);
        Console.WriteLine("I was started by {0}", parent.ProcessName);
        Console.ReadLine();
    }
}

输出从Visual Studio中运行时:

Output when run from Visual Studio:

我被devenv的启动

I was started by devenv