Public colHandle As New Collection
Public Const WM_CLOSE = &H10
Public Const WM_DESTROY = &H2
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Public Function fEnumWindowsCallBack(ByVal hwnd As Long, ByVal lpData As Long) As Long
Dim lParent As Long
Dim lThreadId As Long
Dim lProcessId As Long
'
' This callback function is called by Windows (from the EnumWindows
' API call) for EVERY top-level window that exists. It populates a
' collection with the handles of all parent windows owned by the
' process that we started.
' The lpData argument is the process id of the window(s) to be closed.
fEnumWindowsCallBack = 1
lThreadId = GetWindowThreadProcessId(hwnd, lProcessId)
If lpData = lProcessId Then
lParent = GetParent(hwnd)
If lParent = 0 Then
colHandle.Add hwnd
End If
End If
End Function
Public Function fEnumWindows(ByVal pid As Long) As Boolean
'
' The EnumWindows function enumerates all top-level windows
' by passing the handle of each window, in turn, to an
' application-defined callback function. EnumWindows
' continues until the last top-level window is enumerated or
' the callback function returns FALSE.
' The pid parameter passed to the fEnumWindowsCallBack function is
' the process id of the window(s) to be closed.
Call EnumWindows(AddressOf fEnumWindowsCallBack, pid)
End Function
Sub StopProcess(pid As Long)
Dim i As Long
'
' Enumerate all parent windows for the process to be stopped
'
Call fEnumWindows(pid)
'
' Send a close command to each parent window.
' The app may issue a close confirmation dialog
' depending on how it handles the WM_CLOSE message.
'
'WM_CLOSE instructs the windows to close in their normal fashion as if you manually closed them.
'The window may display a confirmation dialog depending on how it handles the close message.
'To avoid being asked to confirm closing the window, you can send the WM_DESTROY command instead.
For i = 1 To colHandle.Count
Call SendMessage(colHandle.Item(i), WM_CLOSE, 0&, 0&)
Next
End Sub