7,765
社区成员
发帖
与我相关
我的任务
分享
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessID As Long) As Long
Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Private Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Const PROCESS_TERMINATE As Long = (&H1)
Private Const MAX_PATH As Integer = 260
Private Const TH32CS_SNAPPROCESS = &H2
Private Const TH32CS_SNAPTHREAD = &H4
Private Const TH32CS_SNAPMODULE As Long = &H8
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 Sub Command1_Click()
Dim ProNum As Long, PidData() As Long, hProcess As Long, i As Long
ProNum = FindPIDByName("notepad.exe", PidData()) '查找记事本的句柄,为了测试方便请只开一个notepad.exe进程
If ProNum = 0 Then Exit Sub
For i = 0 To ProNum - 1
hProcess = OpenProcess(PROCESS_TERMINATE, False, PidData(i)) '获取进程句柄
Print hProcess '打印句柄
Next
End Sub
Private Function FindPIDByName(ProName As String, PidData() As Long) As Long '返回符合条件的进程ID,保存到数组PidData里
Dim hProSnap As Long, hProID As Long, i As Long
Dim ProInfo As PROCESSENTRY32
ProName = LCase$(ProName)
ProInfo.dwSize = Len(ProInfo)
hProSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
hProID = Process32First(hProSnap, ProInfo)
While hProID <> 0
If LCase$(Left(ProInfo.szExeFile, InStr(1, ProInfo.szExeFile, vbNullChar) - 1)) = ProName Then
ReDim Preserve PidData(i)
PidData(i) = ProInfo.th32ProcessID
i = i + 1
End If
hProID = Process32Next(hProSnap, ProInfo)
Wend
FindPIDByName = i
CloseHandle hProSnap
End Function