在.Net中,如何获得一个进程的父进程?

一个简单的方法:

var performanceCounter = new PerformanceCounter("Process", "Creating Process ID", "Child Process Name");

return Process.GetProcessById((int)performanceCounter.NextValue());

这个方法哪里都好,就是效率不好。创建PerformanceCounter的那句在我的PC要执行1.5秒。 如果这个效率不能令您满意的话,PInvoke是另外的一个选择:

static Process GetParentProcess(Process childProcess)

{

   IntPtr toolhelp32SnapshotHandle = WindowsSdk.CreateToolhelp32Snapshot(WindowsSdk.TH32CS_SNAPPROCESS, 0);

 

   if (toolhelp32SnapshotHandle != IntPtr.Zero)

   {

      var processEntry32 = new Owl.WindowsSdk.PROCESSENTRY32();

      processEntry32.dwSize =

          (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Owl.WindowsSdk.PROCESSENTRY32));

 

      if (WindowsSdk.Process32First(toolhelp32SnapshotHandle, ref processEntry32))

      {

         int parentProcessId = 0;

         do

         {

            if (childProcess.Id == processEntry32.th32ProcessID)

            {

               parentProcessId = (int)processEntry32.th32ParentProcessID;

               break;

            }

         }

         while (parentProcessId == 0 && WindowsSdk.Process32Next(toolhelp32SnapshotHandle, ref processEntry32));

 

         if (parentProcessId > 0)

            return Process.GetProcessById(parentProcessId);

      }

   }

   return null;

}

 

#region Constant defination

internal static uint TH32CS_SNAPPROCESS = 2;

#endregion

 

#region Struct defination

[StructLayout(LayoutKind.Sequential)]

internal struct PROCESSENTRY32

{

   public uint dwSize;

   public uint cntUsage;

   public uint th32ProcessID;

   public IntPtr th32DefaultHeapID;

   public uint th32ModuleID;

   public uint cntThreads;

   public uint th32ParentProcessID;

   public int pcPriClassBase;

   public uint dwFlags;

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]

   public string szExeFile;

};

#endregion

 

#region Kernel32 functions

[DllImport("kernel32.dll", SetLastError = true)]

internal static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

 

[DllImport("kernel32.dll")]

internal static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

 

[DllImport("kernel32.dll")]

internal static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

#endregion

转载于:https://www.cnblogs.com/deepnight/archive/2010/01/27/Query_Parent_Process.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值