我怎样才能让我的应用程序的父进程的PID [英] How can I get the PID of the parent process of my application

查看:145
本文介绍了我怎样才能让我的应用程序的父进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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

这篇关于我怎样才能让我的应用程序的父进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆