我的winform应用程序由另一个应用程序(父应用程序)启动,我需要确定使用C#启动应用程序的应用程序的pid。
在C#中,WMI是更简单的方法。Win32_Process类具有ParentProcessId属性。这是一个例子:
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运行时的输出:
我由devenv开始