chmod chmod - 4 months ago 29
Vb.net Question

How to set focus on other application based on process name VB

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

Answer

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.

Comments