Get the list of processes in VB

Here's the code:

Option Explicit
Private Declare Function EnumProcesses Lib "psapi" (lpIdProcess As Any, ByVal cb As Long, cbNeeded As Long) As Long
Private Declare Function EnumProcessModules Lib "psapi.dll" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function GetModuleFileNameExA Lib "psapi.dll" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const PROCESS_QUERY_INFORMATION = 1024
Private Const PROCESS_VM_READ = 16
Private Sub Form_Load()
EnumP
End Sub
Private Function onEnumM(ByVal strModule As String, ByVal asProcess As Boolean) As Boolean
onEnumM = True
If (Not asProcess) Then
strModule = " " & strModule
End If
Debug.Print strModule
End Function
Private Function EnumP() As Boolean
Dim idProcess() As Long
Dim cb As Long, I As Long
cb = 16
Do
ReDim idProcess(0 To cb - 1) As Long
If EnumProcesses(idProcess(0), cb * 4, I) = 0 Then Exit Function
If I < cb * 4 Then
ReDim idProcess(0 To (I / 4) - 1) As Long
EnumProcesses idProcess(0), cb * 4, I
Exit Do
End If
cb = cb * 2
Loop
Dim bResult As Boolean
bResult = True
For I = LBound(idProcess) To UBound(idProcess)
Dim h As Long
h = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, idProcess(I))
If (h <> 0) Then
bResult = EnumM(h)
CloseHandle h
If (Not bResult) Then Exit For
End If
Next
EnumP = bResult
End Function
Private Function EnumM(ByVal hProcess As Long) As Boolean
Dim hModule() As Long
Dim cb As Long, I As Long
' If the cb is grather than 1 the procedure gets all modules of the process
cb = 2
Do
ReDim hModule(0 To cb - 1) As Long
If EnumProcessModules(hProcess, hModule(0), cb * 4, I) = 0 Then
EnumM = True
Exit Function
End If
If (cb = 1) Then Exit Do
If I < cb * 4 Then
ReDim hModule(0 To (I / 4) - 1) As Long
EnumProcessModules hProcess, hModule(0), cb * 4, I
Exit Do
End If
cb = cb * 2
Loop
For I = LBound(hModule) To UBound(hModule)
Dim s As String
s = String(1024, " ")
s = Mid(s, 1, GetModuleFileNameExA(hProcess, hModule(I), s, 1024))
If (Not onEnumM(s, I = LBound(hModule))) Then
EnumM = False
Exit Function
End If
Next
EnumM = True
End Function
view raw processlst.vb hosted with ❤ by GitHub

Komentar