0

I'm currently developing software in VB.NET (using Visual Studio 2019).

I need to bring a process to the front. I'm using this code:

Private Sub BringInternet_Click(sender As Object, e As EventArgs) Handles BringInternet.Click
    Dim mngcls As ManagementClass = New ManagementClass("Win32_Process")
    Do
        For Each instance As ManagementObject In mngcls.GetInstances()
            If instance("Name").ToString = "msedge.exe" Then
                Dim ID As Integer = instance("ProcessId")
                MsgBox(ID)

                AppActivate(ID)
                Exit Do
            End If
        Next
    Loop While False
End Sub

Sometimes it's working but most of the time it doesn't work. I've already done some research about this but I found nothing about this bug.

Jason Madi
  • 43
  • 1
  • 6

1 Answers1

1

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".