Script for automating a large assortment of AME related actions
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.3 KiB

9 months ago
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. namespace Ameliorated.ConsoleUtils
  5. {
  6. public static class ParentProcess
  7. {
  8. private static readonly uint TH32CS_SNAPPROCESS = 2;
  9. public static string ProcessName = Get().ProcessName;
  10. public static Process Get()
  11. {
  12. try
  13. {
  14. var iParentPid = 0;
  15. var iCurrentPid = Process.GetCurrentProcess().Id;
  16. var oHnd = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  17. if (oHnd == IntPtr.Zero)
  18. return null;
  19. var oProcInfo = new PROCESSENTRY32();
  20. oProcInfo.dwSize =
  21. (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
  22. if (Process32First(oHnd, ref oProcInfo) == false)
  23. return null;
  24. do
  25. {
  26. if (iCurrentPid == oProcInfo.th32ProcessID)
  27. iParentPid = (int)oProcInfo.th32ParentProcessID;
  28. } while (iParentPid == 0 && Process32Next(oHnd, ref oProcInfo));
  29. if (iParentPid > 0)
  30. return Process.GetProcessById(iParentPid);
  31. return null;
  32. } catch (Exception e)
  33. {
  34. return null;
  35. }
  36. }
  37. [DllImport("kernel32.dll", SetLastError = true)]
  38. private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
  39. [DllImport("kernel32.dll")]
  40. private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
  41. [DllImport("kernel32.dll")]
  42. private static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
  43. [StructLayout(LayoutKind.Sequential)]
  44. public struct PROCESSENTRY32
  45. {
  46. public uint dwSize;
  47. public uint cntUsage;
  48. public uint th32ProcessID;
  49. public IntPtr th32DefaultHeapID;
  50. public uint th32ModuleID;
  51. public uint cntThreads;
  52. public uint th32ParentProcessID;
  53. public int pcPriClassBase;
  54. public uint dwFlags;
  55. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  56. public string szExeFile;
  57. }
  58. }
  59. }