问题
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