Restart C# application without actually closing and re-opening?

时间秒杀一切 提交于 2019-12-06 05:27:35

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/13170827/restart-c-sharp-application-without-actually-closing-and-re-opening

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!