It's been a while since I used AppActivate
(back in the VB6 days). Apparently, it's simply a wrapper around the SetForegroundWindow()
Win32 function, meaning that it only brings the window to front (if it's already in a restored state) but it doesn't restore it if minimized.
In order to restore the window and then bring it to front, you need to call ShowWindow()
first and then SetForegroundWindow()
.
First, add this class to your project:
Imports System.Runtime.InteropServices
Public Class ProcessHelper
<DllImport("User32.dll")>
Private Shared Function SetForegroundWindow(handle As IntPtr) As Boolean
End Function
<DllImport("User32.dll")>
Private Shared Function ShowWindow(handle As IntPtr, nCmdShow As Integer) As Boolean
End Function
<DllImport("User32.dll")>
Private Shared Function IsIconic(handle As IntPtr) As Boolean
End Function
Private Const SW_RESTORE As Integer = 9
Public Shared Sub BringProcessToFront(processName As String)
' Modern browsers run on multiple processes.
' We need to find the ones that have a WindowHandle.
Dim processes = Process.GetProcessesByName(processName).
Where(Function(p) p.MainWindowHandle <> IntPtr.Zero)
For Each p As Process In processes
If BringProcessToFront(p) Then Exit Sub
Next
End Sub
Public Shared Function BringProcessToFront(p As Process) As Boolean
Dim windowHandle As IntPtr = p.MainWindowHandle
If IsIconic(windowHandle) Then
ShowWindow(windowHandle, SW_RESTORE)
End If
Return SetForegroundWindow(windowHandle)
End Function
End Class
Then, you can use it like this:
ProcessHelper.BringProcessToFront("msedge") ' Tip: Use the process name without ".exe".