-3

I am starting an application with parameteres, and I want to close my C# application after "Startup.exe" closed. After startup.exe closed the C# application still running, so my question is why WaitForExit() not working for me? And how to solve this issue?

private void button4_Click(object sender, EventArgs e)
 {
 string arg0 = "/connect";
 string arg1 = txtUsername.Text;
 string arg2 = txtPassword.Text;
 string genArgs = arg0+" "+arg1 +" "+ arg2;
 string pathToFile = System.IO.Directory.GetCurrentDirectory()+"/Startup.exe";
 Process runProg = new Process();
 runProg.StartInfo.FileName = pathToFile;
 runProg.StartInfo.Arguments = genArgs;
 runProg.Start();
 runProg.WaitForExit();
 }
WinDev
  • 27
  • 1
  • 9
  • what do you expect `runProg.WaitForExit()` to do?. Hint: it will not close your application. Check [MSDN](https://msdn.microsoft.com/library/system.diagnostics.process.waitforexit(v=vs.110).aspx) – Gian Paolo Dec 11 '16 at 12:54
  • You may want to look at [How to properly exit a C# application](http://stackoverflow.com/questions/12977924/how-to-properly-exit-a-c-sharp-application) – Mathias R. Jessen Dec 11 '16 at 20:10

1 Answers1

3

You're still in the button handler so you're application will just continue to run. If you want to close your application try adding a Environment.Exit to the end of your statement.

private void button4_Click(object sender, EventArgs e)
{
    var arg0 = "/connect";
    var arg1 = txtUsername.Text;
    var arg2 = txtPassword.Text;
    var genArgs = arg0+" "+arg1 +" "+ arg2;
    var pathToFile = System.IO.Directory.GetCurrentDirectory()+"/Startup.exe";

    var runProg = new Process();
    runProg.StartInfo.FileName = pathToFile;
    runProg.StartInfo.Arguments = genArgs;
    runProg.Start();

    Environment.Exit(0);
}

WaitForExit will block until the process you have spawned has terminated before continuing. See - https://msdn.microsoft.com/en-us/library/fb4aw7b8(v=vs.110).aspx

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77