The .net framework’s Process object lacks a means of determining which process invoked it.
There are 3 techniques I have seen for determining this:
- Api Calls
- Iterating through the process table
- Using wmi
This code sample uses the 3rd technique.
Usage:
The code exposes a new “Parent” process function on the standard System.Diagnostics.Process class.
MessageBox.Show(System.Diagnostics.Process.GetCurrentProcess.Parent.Id)
Source:
Imports System.Management
Public Module ProcessExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function Parent(ByVal process As Process) As Process
Return process.GetProcessById(miGetParentProcessId(process.Id))
End Function
Private Function miGetParentProcessId(ByVal processId As Integer) As Integer
Dim loQuery As SelectQuery = New SelectQuery(String.Format("select * from Win32_Process where ProcessId = {0}", processId))
Dim loSearcher As ManagementObjectSearcher = New ManagementObjectSearcher(loQuery)
Dim loProcesses As ManagementObjectCollection = loSearcher.Get()
If loProcesses.Count > 0 Then
Return loProcesses(0)("ParentProcessId")
End If
Return 0
End Function
End Module
References
Kill a specific process – System.Management forum post
Retrieving the Parent Process of a Child when Multiple Instances Exist – Robert Villahermosa
I have a child ID, I passed into the function. Why the parent process PID always = 208?
I have problem with Return line of your code:
Return loProcesses(0)(“ParentProcessId”)
Visual Studio shows error:
Class ‘System.Management.ManagementObjectCollection’ cannot be indexed because it has no default property.
Seems that refference to System.Linq is needed..
Correct!