Introduction
Since .NET Framework 2.0, it supports Application.Restart()
to "shut down the application and start a new instance immediately" as what it introduced in MSDN. Unfortunately, not all developers including myself could not use this function to restart application expectedly. The key to restarting an application properly is where you should code "Application.Restart();
" in.
Background
My use case is need to restart application once configuration has been changed. After referring to some forums' articles, some will guide us to code "Application.Restart();
" within some events, e.g., button click, tool strip menu item click. But, some developers feedback is failure. And, I got an exception "Operation was canceled by the user." After discussions, I realized that right place to code it in is the key to restart application successfully.
Hope the following code sample is helpful to you.
Using the Code
By default, the entry point of a startup application is Program.Main()
. In Main()
, the main form instance will be created and used by Application.Run()
. Hence, Application.Restart()
should be coded within Program.Main()
. Use a simple property to indicate whether there is a need to restart application or end application normally.
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 fm1 = new Form1();
Application.Run(fm1);
if (fm1.ToRestart)
Application.Restart();
}
}
In the main form, e.g., Form1
as in the above sample code, just set property to indicate whether the application should be restarted and/or enforce to close main form.
public partial class Form1 : Form
{
public bool ToRestart = false;
private void button1_Click(object sender, EventArgs e)
{
ToRestart = true;
this.Close();
}