ToyotaMR2
ToyotaMR2

Reputation: 141

Check for open Windows application and wait until it is closed?

I have a pretty simple program where it runs certain steps. Each step should run pragmatically. I am having trouble with a bit of my code. Where I am relying on an application to close (waiting for user to close OUTLOOK ) to execute my next block of code. It launches the first file fine but it reads OUTLOOK as open then it wont work. I wish to make it that when the user closes outlook it will continue and open the next HTML file I have tried to Google for something like wait for exit on this line of code Process[] localByName = Process.GetProcessesByName("OUTLOOK"); but I couldnt find anything

static void Main(string[] args)
{
    var myProcess = new Process { StartInfo = new ProcessStartInfo(@"c:\TestFile1.html") };
    myProcess.Start();

    //Launches the html file 

    Thread.Sleep(1000);

    Process[] localByName = Process.GetProcessesByName("OUTLOOK"); 
    //used for detecting whether outlook is open  

    if (localByName.Length == 0)
    {
        //Only runs when outlook is closed by user 
        var myProcess2 = 
            new Process { StartInfo = new ProcessStartInfo(@"c:\TESTFILE2.html") };

        myProcess2.Start();
    }
    else
    {
        Console.WriteLine("Im not going to work " + localByName.Length);
        Console.ReadLine();
    }
}

Upvotes: 0

Views: 1037

Answers (1)

Sebastian L
Sebastian L

Reputation: 834

You are searching for the Process.WaitForExit()Method ( https://msdn.microsoft.com/library/fb4aw7b8(v=vs.110).aspx)

You can use it like:

foreach(var process in localByName) {
    if(!process.HasExited()) {
        process.WaitForExit();
    }
}

Upvotes: 2

Related Questions