getting PID of process started by Process.start()

前端 未结 4 996
礼貌的吻别
礼貌的吻别 2020-12-01 08:19

I am starting an executable using this code:

Process proc = new Process();
proc.StartInfo.FileName = executablePath;
proc.Start();
proc.WaitForInputIdle();
<         


        
4条回答
  •  攒了一身酷
    2020-12-01 08:46

    An example of how I did it:

        bool started = false;
        var p = new Process();
    
        p.StartInfo.FileName = "notepad.exe";
    
        started = p.Start();
    
        try {
          var procId = p.Id;
          Console.WriteLine("ID: " + procId);
        }
        catch(InvalidOperationException)
        {
            started = false;
        }
        catch(Exception ex)
        {
            started = false;
        }
    

    Otherwise, try using handles like this:
    Using handlers
    Getting handler

    hWnd = (int) process.MainWindowHandle;
    int processId;
    GetWindowThreadProcessId(hWnd, out processId);
    
    [DllImport("user32")]
    static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
    

    Side note:
    What happens if you get the array of process and iterate over them and compare the PIDs?

    Process[] p = Process.GetProcessesByName( "testprogram" );
    foreach(var proc in p)
        Console.WriteLine("Found: "+proc.Id == myExpectedProcId);
    

提交回复
热议问题