Created
May 5, 2010 12:14
-
-
Save mikeobrien/390700 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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