Option Explicit
'============================================================
'//功能:PID获得进程名
'//用法:MsgBox GetProcessNameByProcessId(2960)
'============================================================
Private Declare Function OpenProcess Lib "kernel32.dll" (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.dll" (ByVal hObject 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
Public Function GetProcessNameByProcessId(ByVal Pid As Long) As String
Dim szBuf(1 To 250) As Long
Dim Ret As Long
Dim szPathName As String
Dim nSize As Long
Dim hProcess As Long
Dim SplitStr() As String
hProcess = OpenProcess(&H400 Or &H10, 0, Pid)
If hProcess <> 0 Then
Ret = EnumProcessModules(hProcess, szBuf(1), 250, Pid)
If Ret <> 0 Then
szPathName = Space(260)
nSize = 500
Ret = GetModuleFileNameExA(hProcess, szBuf(1), szPathName, nSize)
SplitStr = Split(szPathName, "\")
GetProcessNameByProcessId = SplitStr(UBound(SplitStr))
End If
End If
Ret = CloseHandle(hProcess)
End Function