【问题标题】:How to set focus on other application based on process name VB如何根据进程名VB设置对其他应用程序的关注
【发布时间】:2012-01-09 08:20:43
【问题描述】:

如何在VB2010中根据进程名称设置对其他应用程序的关注?

我现在可以做的是使用 FindWindow 根据窗口名称将焦点设置在其他应用程序上,然后使用 SetForegroundWindow。以下是我目前拥有的

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

问题是 FindWindow 需要确切的窗口名称才能工作,而我并不总是知道确切的名称。 (因为我的程序打开了用户输入的不同网站,所以我无法控制他们打开的网站)。那么无论如何我可以使用进程名称来设置焦点吗? (在这种情况下为 firefox.exe)欢迎任何其他建议。

谢谢

【问题讨论】:

    标签: vb.net process focus


    【解决方案1】:

    您可以使用System.Diagnostics.Process通过名称查找进程,然后找到窗口标题:

    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
    

    使用静态GetProcessesByName 方法,然后使用MainWindowTitle 属性。对于此示例,您需要 Import System.Diagnostics 来导入正确的命名空间。

    【讨论】:

    • 语法不通请见谅;我没有在这台电脑上安装 VB Express。
    • 难以置信的脆弱;最好希望他们不要改名!已经发生过一次了。
    • @Cody 我不能不同意。但是,OP 询问如何根据进程名称设置焦点。
    【解决方案2】:
    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
    

    然后使用这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2011-11-15
      相关资源
      最近更新 更多