Click here to Skip to main content
15,921,837 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello! I'm trying to write an app which can swap between Internet Explorer windows which are already open in the background. The problem is, these Internet Explorer windows will have the exact same name (Just different PIDs)

What I have tried:

I have tried working with
AppActivate
however, this seems to only accept Window Handles by name.

VB
Function GetObjInts()
        If Process.GetProcessesByName("iexplore").Length >= 1 Then
            For Each ObjProcess As Process In Process.GetProcessesByName("iexplore")
                'Get the list of IDs for us to cycle.
                ObjInts.Add(ObjProcess.Id)
            Next
        End If
End Function


Function Swap()
        For Each Id As Integer In ObjInts
                AppActivate(Id)
                SendKeys.SendWait("~")
            End If
        Next
End Function



Any alternative ideas on how to swap windows with the same name (by PID?) would be appreciated!
Posted
Updated 15-Feb-18 13:19pm

1 solution

You're going to want to use a user32.dll function.

Declare the function like so:
VB
Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As Integer) As Integer


Using the API is easy. Here's an example snippet.
VB
<System.Runtime.InteropServices.DllImport("user32.dll")>
<System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)>
Private Shared Function ShowWindow(ByVal hWnd As IntPtr, ByVal flags As ShowWindowEnum) As Boolean
End Function

<System.Runtime.InteropServices.DllImport("user32.dll")>
Private Shared Function SetForegroundWindow(ByVal hwnd As IntPtr) As Integer
End Function

Private Enum ShowWindowEnum
    Hide = 0
    ShowNormal = 1
    ShowMinimized = 2
    ShowMaximized = 3
    Maximize = 3
    ShowNormalNoActivate = 4
    Show = 5
    Minimize = 6
    ShowMinNoActivate = 7
    ShowNoActivate = 8
    Restore = 9
    ShowDefault = 10
    ForceMinimized = 11
End Enum

Public Sub BringMainWindowToFront(ByVal processName As String)
    Dim bProcess As Process = Process.GetProcessesByName(processName).FirstOrDefault()
    If bProcess IsNot Nothing Then
        If bProcess.MainWindowHandle = IntPtr.Zero Then
            ShowWindow(bProcess.Handle, ShowWindowEnum.Restore)
        End If

        SetForegroundWindow(bProcess.MainWindowHandle)
    Else
        Process.Start(processName)
    End If
End Sub


You can modify BringMainWindowToFront to your own needs (like using PID).

Hope this helps!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900