Private Declare Function GetWindowThreadProcessId Lib "user32" _
(ByVal hwnd As Long, _
lpdwProcessId As Long) As Long
Private Declare Function AttachThreadInput Lib "user32" _
(ByVal idAttach As Long, _
ByVal idAttachTo As Long, _
ByVal fAttach As Long) As Long
Private Declare Function GetForegroundWindow Lib "user32" _
() As Long
Private Declare Function SetForegroundWindow Lib "user32" _
(ByVal hwnd As Long) As Long
Private Declare Function IsIconic Lib "user32" _
(ByVal hwnd As Long) As Long
Private Declare Function ShowWindow Lib "user32" _
(ByVal hwnd As Long, _
ByVal nCmdShow As Long) As Long
Private Const SW_SHOW = 5
Private Const SW_RESTORE = 9
Sub Test()
With CreateObject("InternetExplorer.Application")
.Visible = True
.navigate "http://www.mrexcel.com"
End With
BringWindowToFront Application.hwnd
End Sub
Private Function BringWindowToFront _
(ByVal hwnd As Long) As Boolean
Dim ThreadID1 As Long
Dim ThreadID2 As Long
Dim nRet As Long
On Error Resume Next
' Nothing to do if already in foreground.
If hwnd = GetForegroundWindow() Then
BringWindowToFront = True
Else
'First need to get the thread responsible for this window,
'and the thread for the foreground window.
ThreadID1 = _
GetWindowThreadProcessId(GetForegroundWindow, ByVal 0&)
ThreadID2 = _
GetWindowThreadProcessId(hwnd, ByVal 0&)
'By sharing input state, threads share their concept of
'the active window.
Call AttachThreadInput(ThreadID1, ThreadID2, True)
nRet = SetForegroundWindow(hwnd)
'Restore and repaint.
If IsIconic(hwnd) Then
Call ShowWindow(hwnd, SW_RESTORE)
Else
Call ShowWindow(hwnd, SW_SHOW)
End If
'BringWindowToFront returns TRUE if success.
BringWindowToFront = CBool(nRet)
End If
End Function