' set your application's window caption
App.Caption = System.Guid.NewGuid.ToString.ToUpper
Declare Function EndTask Lib "user32.dll" (ByVal hWnd As IntPtr) As Integer
Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Declare Function GetWindowThreadProcessId Lib "user32.dll" _
(ByVal hWnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer
Declare Function SetLastError Lib "kernel32.dll" (ByVal dwErrCode As Integer) As IntPtr
Public Sub EnsureProcessKilled(ByVal MainWindowHandle As IntPtr, ByVal Caption As String)
SetLastError(0)
' for Excel versions <10, this won't be set yet
If IntPtr.Equals(MainWindowHandle, IntPtr.Zero) Then _
MainWindowHandle = FindWindow(Nothing, Caption)
If IntPtr.Equals(MainWindowHandle, IntPtr.Zero) Then _
Exit Sub ' at this point, presume the window has been closed.
Dim iRes, iProcID As Integer
iRes = GetWindowThreadProcessId(MainWindowHandle, iProcID)
If iProcID = 0 Then ' can’t get Process ID
If EndTask(MainWindowHandle) <> 0 Then Exit Sub ' success
Throw New ApplicationException("Failed to close.")
End If
Dim proc As System.Diagnostics.Process
proc = System.Diagnostics.Process.GetProcessById(ProcessID)
proc.CloseMainWindow()
proc.Refresh()
If proc.HasExited Then Exit Sub
proc.Kill()
End Sub
|