ProcessExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. //----------------------------------------------------------------
  7. //Module Name: $safeprojectname$
  8. //Purpose:
  9. //CopyRight: Muchinfo
  10. //History:
  11. //----------------------------------------------------------------
  12. //DateTime 2016/8/22 14:26:52
  13. //Author
  14. //Description Create
  15. //----------------------------------------------------------------
  16. namespace Muchinfo.MTPClient.Infrastructure.Extensions
  17. {
  18. public static class ProcessExtensions
  19. {
  20. private static string FindIndexedProcessName(int pid)
  21. {
  22. var processName = Process.GetProcessById(pid).ProcessName;
  23. var processByName = Process.GetProcessesByName(processName);
  24. string processIndexdName = null;
  25. for (int index = 0; index < processByName.Length; index++)
  26. {
  27. processIndexdName = index == 0 ? processName : processName + "#" + index;
  28. var procssId = new PerformanceCounter("Process", "ID Process", processIndexdName);
  29. if ((int) procssId.NextValue() == pid)
  30. {
  31. return processIndexdName;
  32. }
  33. }
  34. return processIndexdName;
  35. }
  36. private static Process FindPidFromIndexedProcessName(string indexedProcessName)
  37. {
  38. var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
  39. return Process.GetProcessById((int) parentId.NextValue());
  40. }
  41. public static Process Parent(this Process process)
  42. {
  43. return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
  44. }
  45. }
  46. }