According to msdn SetForegroundWindow only works if one of the following
is
true:
The process is the foreground process.
The process was started by the foreground process.
The process received the last input event.
There is no foreground process.
The foreground process is being debugged.
The foreground is not locked (see LockSetForegroundWindow).
The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT
in SystemParametersInfo).
Windows 2000/XP: No menus are active.
Using the above sequence seems to circumvent these restrictions and forces
the window to the top...
Hi Tom,
thanks for the feedback. You are right, of course, but I don't know if it
helps John.
As I couldn't find a working implementation in VB.NET on groups.google.com
or somewhere else on the net here is some code that worked for me and might
work for John as well:
Private Declare Function GetForegroundWindow _
Lib "user32" () As IntPtr
Private Declare Function SetForegroundWindow _
Lib "user32" (ByVal hWnd As IntPtr) As Boolean
Private Declare Function GetWindowThreadProcessId _
Lib "user32" (ByVal hWnd As IntPtr, _
ByVal lpdwProcessId As IntPtr) As Integer
Private Declare Function AttachThreadInput _
Lib "user32" (ByVal idAttach As Integer, _
ByVal idAttachTo As Integer, ByVal fAttach As Boolean _
) As Boolean
Private Declare Function FindWindow _
Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim hwndApp As IntPtr
Dim hwndForeground As IntPtr
Dim ThreadForeground As Integer
hwndApp = FindWindow("Notepad", "Untitled - Notepad")
If Not hwndApp.Equals(IntPtr.Zero) AndAlso _
Not hwndApp.Equals(GetForegroundWindow) Then
ThreadForeground = GetWindowThreadProcessId(hwndForeground,
IntPtr.Zero)
AttachThreadInput(ThreadForeground, 0, True)
SetForegroundWindow(hwndApp)
AttachThreadInput(ThreadForeground, 0, False)
End If
End Sub
One may have to use Spy++ to get more details about the window that shall be
set to the foreground.
Cheers
Arne Janning