Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function GetShellWindow Lib "user32" () As LongPtr
Private Declare PtrSafe Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As LongPtr, ByVal wFlag As Long) As LongPtr
Private Declare PtrSafe Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As LongPtr, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As Long
Private Declare PtrSafe Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As LongPtr, lpdwProcessId As Long) As Long
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 TerminateProcess Lib "kernel32" (ByVal hProcess As LongPtr, ByVal uExitCode As Long) As Long
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As LongPtr) As Long
#Else
Private Declare Function GetShellWindow Lib "user32" () As Long
Private Declare Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As Long, ByVal wFlag As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId 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 TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
#End If
Private Const PROCESS_TERMINATE = &H1
Private Const GW_HWNDPREV = 3
Private Const WM_CLOSE = &H10
Sub KillAllByClassName(ByVal ClassName As String, Optional ByVal ForceKill As Boolean = False)
#If VBA7 Then
Dim hwnd As LongPtr, hProc As LongPtr
#Else
Dim hwnd As Long, hProc As Long
#End If
Dim ret As Long, sBuffer As String * 256
Dim hPid As Long, lExitCode As Long
hwnd = GetShellWindow
Do While hwnd <> 0
ret = GetClassName(hwnd, sBuffer, Len(sBuffer))
If Left(sBuffer, ret) = ClassName Then
If ForceKill Then
Call GetWindowThreadProcessId(hwnd, hPid)
hProc = OpenProcess(PROCESS_TERMINATE, 0, hPid)
Call TerminateProcess(hProc, lExitCode)
Call CloseHandle(hProc)
Else
Call PostMessage(hwnd, WM_CLOSE, 0, 0)
End If
End If
hwnd = GetNextWindow(hwnd, GW_HWNDPREV)
Loop
End Sub