如何获取我的应用程序的父进程的 PID [英] How can I get the PID of the parent process of my application
本文介绍了如何获取我的应用程序的父进程的 PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 winform 应用程序由另一个应用程序(父应用程序)启动,我需要确定使用 C# 启动我的应用程序的应用程序的 pid.
My winform application is launched by another application (the parent), I need determine the pid of the application which 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
这篇关于如何获取我的应用程序的父进程的 PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文