4

How can i get all of my internal code to work as if I used Application.Restart(), but without actually having the program have to close and reopen?

Adam Johns
  • 35,397
  • 25
  • 123
  • 176
  • What exactly do you want to do? Reset a bunch of application state? Run a specific form? Why can't you use `Application.Restart()`? – D Stanley Nov 01 '12 at 04:11
  • 3
    That depends on the design of your internal code. – Andrew Cooper Nov 01 '12 at 04:13
  • Is it because you are losing the debugging state while running it from VS? If so you can have the application being run in a while loop, and you can set a condition yourself to check whether while condition is met. I have successfully used it in production code. – nawfal Nov 01 '12 at 05:57
  • 1
    @DStanley, i don't want the user to see the application close and reopen when they click cancel. I just want all the internal code to work as if they had used Application.Restart() – Adam Johns Nov 01 '12 at 17:20
  • If you restart.you application, then the user **should definitively** see it. And instead of trying to hide problems, you should definitively fix them. And if required, hire more competent developers or rewrite the application if it was poorly writen. – Phil1970 Sep 02 '17 at 12:23

1 Answers1

6

Depending on the design of your application it could be as simple as starting a new instance of your main form and closing any existing form instances. Any application state outside of form variables would need to be reset as well. There's not a magic "reset" button for applications like it sounds like you're searching for.

One way would be to add a loop to Program.cs to keep the app running if the form closes after a "reset":

static class Program
{
    public static bool KeepRunning { get; set; }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        KeepRunning = true;
        while(KeepRunning)
        {
            KeepRunning = false;
            Application.Run(new Form1());
        }
    }
}

and in your form (or toolbar, etc.) set the KeepRunning variable to true:

private void btnClose_Click(object sender, EventArgs e)
{
    // close the form and let the app die
    this.Close();
}

private void btnReset_Click(object sender, EventArgs e)
{
    // close the form but keep the app running
    Program.KeepRunning = true;
    this.Close();
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240