retesere20

get process parent c#

Jul 26th, 2019
137
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. /*
  3. /// <summary>
  4. /// A utility class to determine a process parent.
  5. /// </summary>
  6. [StructLayout(LayoutKind.Sequential)]
  7. public struct ParentProcessUtilities
  8. {
  9. // These members must match PROCESS_BASIC_INFORMATION
  10. internal IntPtr Reserved1;
  11. internal IntPtr PebBaseAddress;
  12. internal IntPtr Reserved2_0;
  13. internal IntPtr Reserved2_1;
  14. internal IntPtr UniqueProcessId;
  15. internal IntPtr InheritedFromUniqueProcessId;
  16.  
  17. [DllImport("ntdll.dll")]
  18. private static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, ref ParentProcessUtilities processInformation, int processInformationLength, out int returnLength);
  19.  
  20. /// <summary>
  21. /// Gets the parent process of the current process.
  22. /// </summary>
  23. /// <returns>An instance of the Process class.</returns>
  24. public static Process GetParentProcess()
  25. {
  26. return GetParentProcess(Process.GetCurrentProcess().Handle);
  27. }
  28.  
  29. /// <summary>
  30. /// Gets the parent process of specified process.
  31. /// </summary>
  32. /// <param name="id">The process id.</param>
  33. /// <returns>An instance of the Process class.</returns>
  34. public static Process GetParentProcess(int id)
  35. {
  36. Process process = Process.GetProcessById(id);
  37. return GetParentProcess(process.Handle);
  38. }
  39.  
  40. /// <summary>
  41. /// Gets the parent process of a specified process.
  42. /// </summary>
  43. /// <param name="handle">The process handle.</param>
  44. /// <returns>An instance of the Process class.</returns>
  45. public static Process GetParentProcess(IntPtr handle)
  46. {
  47. ParentProcessUtilities pbi = new ParentProcessUtilities();
  48. int returnLength;
  49. int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
  50. if (status != 0)
  51. throw new Win32Exception(status);
  52.  
  53. try
  54. {
  55. return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
  56. }
  57. catch (ArgumentException)
  58. {
  59. // not found
  60. return null;
  61. }
  62. }
  63. }
  64. */
RAW Paste Data