ExtensionMethod.NET Home of 874 C#, Visual Basic, F# and Javascript extension methods

GetParentProcessID

The method extends the Process class to retrieve (if possible) the id of the parent process. The method uses P/Invoke to access the system data. It uses API in kenrnel32.dll (CreateToolhelp32Snapshot, Process32First, Process32Next).

Source

Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices

Public Module ProcessExtension
    <DllImport("kernel32.dll", SetLastError:=True)>
    Private Function CreateToolhelp32Snapshot(ByVal dwFlags As SnapshotFlags, ByVal th32ProcessID As UInteger) As IntPtr
    End Function

    <DllImport("kernel32.dll")> _
    Private Function Process32First(ByVal hSnapshot As IntPtr, ByRef lppe As PROCESSENTRY32) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Private Function Process32Next(ByVal hSnapshot As IntPtr, ByRef lppe As PROCESSENTRY32) As Boolean
    End Function


    <Flags()> _
    Private Enum SnapshotFlags As Integer
        HeapList = &H1
        Process = &H2
        Thread = &H4
        [Module] = &H8
        Module32 = &H10
        Inherit = &H80000000
        All = &H1F
    End Enum

    <StructLayout(LayoutKind.Sequential)> _
    Private Structure PROCESSENTRY32
        Public dwSize As UInteger
        Public cntUsage As UInteger
        Public th32ProcessID As UInteger
        Public th32DefaultHeapID As IntPtr
        Public th32ModuleID As UInteger
        Public cntThreads As UInteger
        Public th32ParentProcessID As UInteger
        Public pcPriClassBase As Integer
        Public dwFlags As UInteger
        <VBFixedString(260), MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> Public szExeFile As String
    End Structure

    <Extension()>
    Public Function GetParentProcessID(ByVal process As Process) As UInteger?
        If process Is Nothing Then Throw New NullReferenceException()
        Dim retval As UInteger? = Nothing
        Dim snapShot = CreateToolhelp32Snapshot(SnapshotFlags.Process, 0)
        If snapShot <> IntPtr.Zero Then
            Dim procEntry As New PROCESSENTRY32
            procEntry.dwSize = CUInt(Marshal.SizeOf(GetType(PROCESSENTRY32)))
            Dim okFlag = Process32First(snapShot, procEntry)
            While (okFlag)
                If process.Id = procEntry.th32ProcessID Then
                    retval = procEntry.th32ParentProcessID
                    Exit While
                Else
                    okFlag = Process32Next(snapShot, procEntry)
                End If
            End While
        End If
        Return retval
    End Function
End Module

Example

Dim parentId = Process.GetCurrentProcess.GetParentProcessID()

Author: Massimo Bonanni

Submitted on: 5 aug 2010

Language: VB

Type: System.Diagnostic.Process

Views: 6823