Prendendo spunto da un post apparso sul newsgroup dedicato a Visual Basic (http://social.msdn.microsoft.com/Forums/it-IT/visualbasicit/threads), vorrei proporvi un metodo di estensione per la classe Process che, utilizzando P/Invoke, recupera l’identificativo del processo padre di un processo (se esiste), cioè l’identificativo del processo che ha aperto il processo.
Il modulo che definisce il metodo di estensione è il seguente:
- 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
Grazie al metodo di estensione possiamo semplicemente scrivere
- .
- Dim parentId = Process.GetCurrentProcess.GetParentProcessID()
- .
- .
Commenti