Option Explicit
Private Const MAX_PATH As Long = 260
Private Type PROCESSENTRY32
dwSize As Long
cntUsage As Long
th32ProcessID As Long
th32DefaultHeapID As Long
th32ModuleID As Long
cntThreads As Long
th32ParentProcessID As Long
pcPriClassBase As Long
dwFlags As Long
szExeFile As String * MAX_PATH
End Type
Private Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Private Const TH32CS_SNAPPROCESS As Long = 2&
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Sub Form_Load()
Dim MyProc As String
MyProc = "explorer.exe"
Me.Caption = FindProcessID(MyProc)
End Sub
Private Function FindProcessID(ByVal pExename As String) As Long
Dim ProcessID As Long, hSnapShot As Long
Dim uProcess As PROCESSENTRY32, rProcessFound As Long
Dim Pos As Integer, szExename As String
hSnapShot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
If hSnapShot = -1 Then
Exit Function
End If
'Initialize uProcess with correct size
uProcess.dwSize = Len(uProcess)
rProcessFound = ProcessFirst(hSnapShot, uProcess)
Do While rProcessFound
Pos = InStr(1, uProcess.szExeFile, vbNullChar)
If Pos Then
szExename = Left$(uProcess.szExeFile, Pos - 1)
End If
If LCase$(szExename) = LCase$(pExename) Then
ProcessID = uProcess.th32ProcessID
Exit Do
Else
rProcessFound = ProcessNext(hSnapShot, uProcess)
End If
Loop
CloseHandle hSnapShot
FindProcessID = ProcessID
End Function