Skip to content

Instantly share code, notes, and snippets.

@mikeobrien
Created May 5, 2010 12:14
Show Gist options
  • Save mikeobrien/390700 to your computer and use it in GitHub Desktop.
Save mikeobrien/390700 to your computer and use it in GitHub Desktop.
public static class ProcessExtensions
{
public static Process GetParent(this Process child)
{
int parentPid = 0;
IntPtr hnd = Kernel32.CreateToolhelp32Snapshot(Kernel32.TH32CS_SNAPPROCESS, 0);
if (hnd == IntPtr.Zero)
return null;
Kernel32.PROCESSENTRY32 processInfo = new Kernel32.PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(Kernel32.PROCESSENTRY32)) };
if (Kernel32.Process32First(hnd, ref processInfo) == false) return null;
do
{
if (child.Id == processInfo.th32ProcessID)
parentPid = (int)processInfo.th32ParentProcessID;
}
while (parentPid == 0 && Kernel32.Process32Next(hnd, ref processInfo));
if (parentPid > 0)
return Process.GetProcessById(parentPid);
else
return null;
}
}
internal static class Kernel32
{
public static uint TH32CS_SNAPPROCESS = 2;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
};
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll")]
public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll")]
public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment