查找 PID VB.net

Find PID VB.net

我正在尝试在我的游戏中制作一个服务器启动器。我必须使用不同的配置启动 GameServer.exe。
GameServer.exeGameServer1.cfg
GameServer.exeGameServer2.cfg
GameServer.exe GameServer3.cfg 等等

这是我必须启动每个 .exe 和 .cfg 的当前代码

Private Sub GS1_Click(sender As Object, e As EventArgs) Handles GS1.Click
    Dim path As String = Directory.GetCurrentDirectory()
    Dim gameservercfg As String = GameServer1.Text
    Dim newpath As String = path + ("\")
    System.Diagnostics.Process.Start(newpath + "GameServer.exe ", gameservercfg)
End Sub

这是我按进程名称重新启动它的代码。

Private Sub GSRES_Click(sender As Object, e As EventArgs) Handles GSRES.Click
    Dim path As String = Directory.GetCurrentDirectory()
    Dim gameservercfg As String = GameServer.Text
    Dim newpath As String = path + ("\")
    Dim p() As Process

    p = Process.GetProcessesByName("GameServer")
    If p.Count > 0 Then
        ' Process is running
        Process.GetProcessesByName("GameServer")(0).Kill()
        System.Diagnostics.Process.Start(newpath + "GameServer.exe ", gameservercfg)
    Else
        ' Process is not running
        MsgBox("GameServer is not running!")
    End If
End Sub

使用该代码,它正在重新启动随机游戏服务器。
问题是,我如何通过进程 ID 而不是进程名称来做到这一点?

不确定您到底想做什么...但是如果现有游戏实例 运行 在再次启动它之前,这将杀死它:

Private Games As New Dictionary(Of String, Process)

Private Sub GS1_Click(sender As Object, e As EventArgs) Handles GS1.Click
    Dim gameservercfg As String = GameServer1.Text
    Dim Key As String = gameservercfg.ToUpper

    If Games.ContainsKey(Key) Then
        If Not Games(Key).HasExited Then
            Games(Key).Kill()
        End If
        Games.Remove(Key)
    End If

    Dim psi As New ProcessStartInfo
    psi.FileName = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "GameServer.exe")
    psi.WorkingDirectory = System.IO.Path.GetDirectoryName(psi.FileName)
    psi.Arguments = gameservercfg
    Games.Add(Key, System.Diagnostics.Process.Start(psi))
End Sub