Bring application to Front

This seems to get asked about every six months. Here’s how I handle it. Remember, anything in <…> needs to be replaced with your app’s info.

' We need to know the exact name of the main window if we want to bring the first instance to the front.
' So we set it here and retrieve it for the window in its Open event
MainWindowTitle = <whatever you name your application's main or starting window>

// Look to see if the app is already executing
Dim s As shell = New Shell
s.Execute ("tasklist /fo CSV")
Dim theString As String = s.Result
Dim theStringArray () As String
theStringArray = theString.Split (<your App's Name>)
If theStringArray.LastIndex > 1 Then // There's more than one instance in the list of processes that are running
  Soft Declare Function FindWindowA Lib "User32" (className As Integer, title As CString) As Integer
  Soft Declare Function FindWindowW Lib "User32" (className As Integer, title As WString) As Integer
  
  // Find the window via an exact match using FindWindow
  Dim handle As Integer
  If System.IsFunctionAvailable ("FindWindowW", "User32") Then
    handle = FindWindowW (0, MainWindowTitle)
  Else
    handle = FindWindowA (0, MainWindowTitle)
  End If
  
  // If we found a handle, then we want to bring it to the front
  If handle <> 0 Then
    Var i As Integer
    Declare Function ShowWindow Lib "User32" (hWnd As Integer, nCmdShow As Integer) As Integer
    Declare Function BringWindowToTop Lib "User32" (hWnd As Integer) As Integer
    Declare Sub SetForegroundWindow Lib "User32" (hwnd As Integer)
    i = ShowWindow (handle, 1)
    i = BringWindowToTop (handle)
    SetForegroundWindow (handle)
   // and lastly we kill ourself and let the original one run.
    Quit
  End If
  
End If

This doesn’t send any information between the instances of the app. It merely finds and brings the first one to the front and lets the second instance go away.

2 Likes