Form1.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Diagnostics;
  3. using System.Windows.Forms;
  4. namespace TestProcess
  5. {
  6. public static class ProcessExtensions
  7. {
  8. private static string FindIndexedProcessName(int pid)
  9. {
  10. var processName = Process.GetProcessById(pid).ProcessName;
  11. var processesByName = Process.GetProcessesByName(processName);
  12. string processIndexdName = null;
  13. for (var index = 0; index < processesByName.Length; index++)
  14. {
  15. processIndexdName = index == 0 ? processName : processName + "#" + index;
  16. var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
  17. if ((int)processId.NextValue() == pid)
  18. {
  19. return processIndexdName;
  20. }
  21. }
  22. return processIndexdName;
  23. }
  24. private static Process FindPidFromIndexedProcessName(string indexedProcessName)
  25. {
  26. var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
  27. return Process.GetProcessById((int)parentId.NextValue());
  28. }
  29. public static Process Parent(this Process process)
  30. {
  31. return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
  32. }
  33. }
  34. public partial class Form1 : Form
  35. {
  36. public Form1()
  37. {
  38. InitializeComponent();
  39. }
  40. private void Form1_Load(object sender, EventArgs e)
  41. {
  42. string sysdir = Environment.GetFolderPath(Environment.SpecialFolder.System);
  43. MessageBox.Show(sysdir);
  44. string pfile = Process.GetCurrentProcess().Parent().ProcessName;
  45. MessageBox.Show(pfile);
  46. }
  47. }
  48. }