Search code examples
vb.netprocesspidrestartprocess.start

Find PID VB.net


I am trying to make a server launcher in my game. I have to launch GameServer.exe with different configs.
GameServer.exe GameServer1.cfg
GameServer.exe GameServer2.cfg
GameServer.exe GameServer3.cfg etc.

Here's the current code I have to start each of those .exe's and .cfg's

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

And here's my code to restart it by process name.

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

With that code, it's restarting random gameservers.
Question is, how do I do that by ProcessID instead of Process name?


Solution

  • Not sure exactly what you're after here...but this will kill the existing game instance if it's running before starting it again:

    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