Kevin Spencer said:
Well you can. It's just not easy.
Here's how to do it in VB.
Declare Function CreateToolhelp32Snapshot _
Lib "KERNEL32.DLL" (ByVal dwFlags As Integer, _
ByVal th32ProcessID As Integer) As Integer
Declare Function Process32First Lib "KERNEL32.DLL" _
(ByVal hSnapshot As Integer, ByVal PE As Byte()) As Integer
Declare Function Process32Next Lib "KERNEL32.DLL" _
(ByVal hSnapshot As Integer, ByVal PE As Byte()) As Integer
Declare Function CloseHandle Lib "KERNEL32.DLL" _
(ByVal hObject As Integer) As Integer
Const TH32CS_SNAPPROCESS As Integer = 2
Const SIZEOF_PROCESSENTRY32 As Integer = 564
Const SIZE_OFFSET = 0
Const PROCESS_OFFSET = 8
Const PARENT_OFFSET = 24
'// typedef struct tagPROCESSENTRY32
'// {
'// DWORD dwSize;
'// DWORD cntUsage;
'// DWORD th32ProcessID;
'// DWORD th32DefaultHeapID;
'// DWORD th32ModuleID;
'// DWORD cntThreads;
'// DWORD th32ParentProcessID;
'// LONG pcPriClassBase;
'// DWORD dwFlags;
'// TCHAR szExeFile[MAX_PATH];
'// DWORD th32MemoryBase;
'// DWORD th32AccessKey;
'// } PROCESSENTRY32;
Function GetParentProcessID(ByVal id As Integer) As Integer
Dim b(564 - 1) As Byte
'write the size into the structure
BitConverter.GetBytes(SIZEOF_PROCESSENTRY32).CopyTo(b, SIZE_OFFSET)
Dim h As Integer = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
Try
Dim rv As Integer = Process32First(h, b)
If rv <> 1 Then
Throw New Exception("Could not enumerte processes.")
End If
While rv = 1
Dim pid As Integer = BitConverter.ToInt32(b, PROCESS_OFFSET)
Dim parent As Integer = BitConverter.ToInt32(b, PARENT_OFFSET)
If pid = id Then
Return parent
End If
rv = Process32Next(h, b)
End While
Finally
CloseHandle(h)
End Try
Return -1
End Function
Then to use it
'get the target process id (here the current process)
Dim pid As Integer =
GetParentProcessID(System.Diagnostics.Process.GetCurrentProcess.Id)
'get the parent process
Dim parent As System.Diagnostics.Process =
System.Diagnostics.Process.GetProcessById(pid)
This information is also available from the performance counters under
Process>[Instance]>Creating Process ID,
but you must enumerate the instances and identify the target process by
Process>[Instance]>ID Process
which is slow.
David