检查进程是否正在运行,然后切换到它?

时间:2015-07-07 20:24:26

标签: vb.net visual-studio

我有以下代码来检查' chrome'单击Button1时正在运行。如果没有,它会启动chrome。这有效,但我不知道If语句中所需的代码,如果已经运行,则切换到chrome。希望这是我非常简单的事情。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If Process.GetProcessesByName("chrome").Count > 0 Then

       ??**SHOW RUNNING APPLICATION**??

    Else
        Process.Start("C:\Program Files\Google\Chrome\Application\chrome.exe")
    End If


End Sub

1 个答案:

答案 0 :(得分:4)

正如我在上面的评论中所提到的,Chrome starts many instances of itself. Each tab has its own process, so how are you going to tell it which one to switch to?。这取决于最小化窗口时选择的选项卡,或者它最小化到任务栏。下面应该帮助你,它经过了试验和测试。唯一的问题是,如果你打开Chrome并且有多个标签就可以了,但是如果你创建另一个Chrome实例它将不会显示第二个实例,它只会提出第一个实例。如果你关闭第一个实例,第二个实例当然会出现。

Public Class Form1

#Region "DLL Imports"
    <System.Runtime.InteropServices.DllImport("User32.dll")> _
    Private Shared Function SetForegroundWindow(handle As IntPtr) As Boolean
    End Function

    <System.Runtime.InteropServices.DllImport("User32.dll")> _
    Private Shared Function ShowWindow(handle As IntPtr, nCmdShow As Integer) As Boolean
    End Function

    <System.Runtime.InteropServices.DllImport("User32.dll")> _
    Private Shared Function IsIconic(handle As IntPtr) As Boolean
    End Function
#End Region

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       StartOrShowProcess("chrome")
    End Sub


    Private Sub StartOrShowProcess(ByVal strProcessName As String)
        Try
            Dim handle As IntPtr
            Dim proc As Process() = Process.GetProcessesByName(strProcessName)
            If proc.Count > 0 Then
                For Each procP As Process In proc
                    handle = procP.MainWindowHandle
                    If handle <> 0 AndAlso IsIconic(handle) Then 'Do we have a handle and is it minimized?
                        ShowWindow(handle, 9)
                        SetForegroundWindow(handle)
                    End If
                Next
            Else 'Not running or started...
                Process.Start(strProcessName)
            End If

        Catch ex As Exception
            'Handle your error...
        End Try
    End Sub


End Class