C#获取当前进程的父级进程
作者:C/S框架网  发布日期:2018-07-26 15:17:00
  C#获取当前进程的父级进程


C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
   public static class ProcessExtensions
   {
      private static string FindIndexedProcessName(int pid)
      {
         var processName = Process.GetProcessById(pid).ProcessName;
         var processesByName = Process.GetProcessesByName(processName);
         string processIndexdName = null;
         for (var index = 0; index < processesByName.Length; index++)
         {
            processIndexdName = index == 0 ? processName : processName + "#" + index;
            var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
            if ((int)processId.NextValue() == pid)
            {
               return processIndexdName;
            }
         }
         return processIndexdName;
      }
      
      private static Process FindPidFromIndexedProcessName(string indexedProcessName)
      {
         var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
         return Process.GetProcessById((int)parentId.NextValue());
      }
      
      public static Process Parent(this Process process)
      {
         return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
      }
   }

   class Program
   {
      static void Main(string[] args)
      {//测试
         Console.WriteLine(Process.GetCurrentProcess().Parent().ProcessName);
      }
   }
}


//来源:C/S框架网(www.csframework.com) QQ:23404761



上一篇 下一篇