1

How can I set focus on other application based on process name in VB2010?

What I can do now is set focus on other application based on windows name using FindWindow then use SetForegroundWindow. Below is what I currently have

        Dim theHandle As IntPtr
        theHandle = FindWindow(Nothing, "Gmail: Email from Google")
        If theHandle <> IntPtr.Zero Then
        SetForegroundWindow(theHandle)

The problem is that FindWindow need exact windows name to works and I don't always know the exact name. (Because my program open up different website that the user enter, so I have no control over they site they open). So is there anyway that I can set focus using the process name instead? (in this case firefox.exe) Any other suggestions are welcome.

Thanks

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
chmod
  • 129
  • 1
  • 1
  • 11

2 Answers2

1

You can use System.Diagnostics.Process to look up a process by name and then find the window title:

For Each app As Process In Process.GetProcessesByName("firefox")
    Dim theHandle As IntPtr = FindWindow(Nothing, app.MainWindowTitle)
    If theHandle <> IntPtr.Zero Then
        SetForegroundWindow(theHandle)
    End If
Next

Use the static GetProcessesByName method and then the MainWindowTitle property. For this sample you would need Import System.Diagnostics to import the right namespace.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Abraham
  • 479
  • 7
  • 23
0
Private Sub ActivateApp(ByVal pID As Integer)
        Dim p As Process = Process.GetProcessById(pID)
        If p IsNot Nothing Then
            SetForegroundWindow(p.MainWindowHandle)
        End If
    End Sub

Then use this:

ActivateApp(System.Diagnostics.Process.GetCurrentProcess.Id)
SendKeys.SendWait("~")