Friday, March 2, 2012

Restart Windows Forms and Console Applications

In this post I quickly want to show, how to restart C# applications.
For Windows Forms Applications one command suffices:
Application.Restart();

But what actually is behind it, or if someone wants to "personalize" this process, is the following:
The current application is restarted as an pown process and the old instance is closed, which leads us to this manual code for Windows Forms Applications:

// create new process
System.Diagnostics.Process NewInstance = new System.Diagnostics.Process();
// link it to the application
NewInstance.StartInfo.FileName = Application.ExecutablePath;
// start new instance
NewInstance.Start();
// quit current instance
Application.Exit();

This method is especially interesting for console applications, since they do not provide the command Application.Restart().
The above code also works for them, just one line has to be adapted, since of course Application.ExecutablePath is also not avaible:
NewInstance.StartInfo.FileName = System.Threading.Thread.GetDomain().BaseDirectory + System.Threading.Thread.GetDomain().FriendlyName; (on this way we determine via the class Threading application path and application name)

No comments:

Post a Comment