Ever wanted to identify the Process that started another process (for example you might want to find out which process launched your application) ? Well I’ve finally got some code working that gets the ID of the process that created the process you specify.
Here’s the API definitions:
PROCESSBASICINFORMATION As UInteger
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack:=1)> _
Public Structure Process_Basic_Information
Public ExitStatus As IntPtr
Public PepBaseAddress As IntPtr
Public AffinityMask As IntPtr
Public BasePriority As IntPtr
Public UniqueProcessID As IntPtr
Public InheritedFromUniqueProcessId As IntPtr
<System.Runtime.InteropServices.DllImport(“ntdll.dll”, EntryPoint:=“NtQueryInformationProcess”)> _
Public Shared Function NtQueryInformationProcess(ByVal handle As IntPtr, ByVal processinformationclass As UInteger, ByRef ProcessInformation As Process_Basic_Information, ByVal ProcessInformationLength As Integer, ByRef ReturnLength As UInteger) As Integer
and here’s an example of using it to find the parent process ID of an instance of Notepad:
‘Create an instance of our API structure – we will pass
‘this to the API function in a moment
ProccessInfo As New
‘A quick and dirty example of getting the handle of a specific process
Dim ProcHandle As IntPtr = Process.GetProcessesByName(“Notepad”)(0).Handle
‘Used as an output parameter by the API function
Dim RetLength As UInteger
‘Here we actually call the function and pass in the relevant information
NtQueryInformationProcess(ProcHandle, PROCESSBASICINFORMATION, ProccessInfo, Marshal.SizeOf(ProccessInfo), RetLength)
‘We should really check to make sure the function returned 0 (success) before we try to
‘use the data but this is just an example
‘Show the parent process ID in a messagebox
MessageBox.Show(“Parent ID: “ & ProccessInfo.InheritedFromUniqueProcessId.ToString)
Obviously you can then use Process.GetProcessById to get a Process object for that process and gather useful information such as the name etc.
Note that the Microsoft documentation for this particular API states that it is an internal system call and as such may change or be removed etc without warning from future versions of Windows. However, I’ve tested the code above on Windows XP 32 bit and Windows 7 64 bit and it worked perfectly on both.
As always, let me know if you find this code useful!