重新启动 C# 应用程序而不实际关闭和重新打开? [英] Restart C# application without actually closing and re-opening?
问题描述
如何让我的所有内部代码像使用 Application.Restart() 一样工作,但实际上不必关闭并重新打开程序?
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?
推荐答案
根据应用程序的设计,它可以像启动主窗体的新实例并关闭任何现有窗体实例一样简单.表单变量之外的任何应用程序状态也需要重置.对于听起来像您正在搜索的应用程序,没有神奇的重置"按钮.
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.
一种方法是向 Program.cs
添加一个循环,以在表单在重置"后关闭时保持应用程序运行:
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());
}
}
}
并在您的表单(或工具栏等)中将 KeepRunning
变量设置为 true
:
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();
}
这篇关于重新启动 C# 应用程序而不实际关闭和重新打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!