#If VBA7 Then
Private Declare PtrSafe Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As LongPtr, ByRef lpdwProcessId As Long) As Long
Private Declare PtrSafe Function GetClipBoardOwner Lib "user32" Alias "GetClipboardOwner" () As LongPtr
Private Declare PtrSafe Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As LongPtr
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As LongPtr) As Long
Private Declare PtrSafe Function GetModuleFileNameExA Lib "psapi" (ByVal hProcess As LongPtr, ByVal hModule As LongPtr, ByVal lpFileName As String, ByVal nSize As Long) As Long
#Else
Private Enum LongPtr
[_]
End Enum
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As LongPtr, ByRef lpdwProcessId As Long) As Long
Private Declare Function GetClipBoardOwner Lib "user32" Alias "GetClipboardOwner" () As LongPtr
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As LongPtr
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As LongPtr) As Long
Private Declare Function GetModuleFileNameExA Lib "psapi" (ByVal hProcess As LongPtr, ByVal hModule As LongPtr, ByVal lpFileName As String, ByVal nSize As Long) As Long
#End If
Private Const PROCESS_QUERY_INFORMATION As Long = &H400
Private Const PROCESS_VM_READ As Long = &H10
Private Function GetProcessIDFromHwnd(ByVal hwnd As LongPtr) As Long
Dim ProcessId As Long, ThreadId As Long
ThreadId = GetWindowThreadProcessId(hwnd, ProcessId)
If ThreadId <> 0 Then
GetProcessIDFromHwnd = ProcessId
End If
End Function
Private Function GetFileNameFromPath(ByVal FilePath As String) As String
Dim FileParts() As String
FileParts = Split(FilePath, "\")
If UBound(FileParts) >= 0 Then
GetFileNameFromPath = FileParts(UBound(FileParts))
End If
End Function
Private Function GetProcessName(ByVal ProcessId As Long) As String
Dim hProcess As LongPtr
Dim ProcessPath As String
Dim Length As Long
On Error GoTo ErrHandler
ProcessPath = String(260, Chr$(0))
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, ProcessId)
If hProcess <> 0 Then
Length = GetModuleFileNameExA(hProcess, 0, ProcessPath, 260)
If Length > 0 Then
ProcessPath = Left$(ProcessPath, Length)
GetProcessName = GetFileNameFromPath(ProcessPath)
End If
ErrHandler:
CloseHandle hProcess
End If
End Function