How to get the ExitCode of a running process

I am writing an application to test the exit code of another application. The application that I am monitoring can be started, so I test it using Process.GetProcessesByName. If it exists, I check the exit code after the WaitForExit call, but when I do, I get an exception:

"This object was not started, so the requested information could not be determined."

If I start the process (if not already running) it doesn't give me an exception.

(Windows 8.1)

So how do I know what ExitCode is when I haven't started the process yet? The only option I can think of is to write the output code to a text file on exit and read what's in ...

+3


source to share


1 answer


System.Diagnostics.Process provides events that you can access after setting EnableRaisingEvents to true:

    int processId = 0; // TODO: populate this variable
    var proc = System.Diagnostics.Process.GetProcessById(processId);
    proc.EnableRaisingEvents = true;
    proc.Exited += ProcessEnded;

      

Event handler:



    private void ProcessEnded(object sender, EventArgs e)
    {
        var process = sender as Process;
        if (process != null)
        {
            var test = process.ExitCode;
        }
    }

      

the test variable now contains the exit code.

Tested on Windows 8.1

+6


source







All Articles