【问题标题】:Restart C# application without actually closing and re-opening?重新启动 C# 应用程序而不实际关闭和重新打开?
【发布时间】:2012-11-01 04:09:11
【问题描述】:

如何让我的所有内部代码像使用 Application.Restart() 一样工作,但实际上不必关闭并重新打开程序?

【问题讨论】:

  • 你到底想做什么?重置一堆应用程序状态?运行特定的表格?为什么不能使用Application.Restart()
  • 这取决于你的内部代码的设计。
  • 是不是因为你从VS运行它时失去了调试状态?如果是这样,您可以让应用程序在 while 循环中运行,您可以自己设置条件来检查是否满足 while 条件。我已经在生产代码中成功使用了它。
  • @DStanley,我不希望用户在单击取消时看到应用程序关闭并重新打开。我只希望所有内部代码都能像使用 Application.Restart() 一样工作
  • 如果您重新启动应用程序,那么用户应该明确看到它。而不是试图隐藏问题,你应该明确地解决它们。如果需要,请聘请更有能力的开发人员,或者如果应用程序写得不好,则重写它。

标签: c# restart


【解决方案1】:

根据应用程序的设计,它可以像启动主表单的新实例并关闭任何现有表单实例一样简单。表单变量之外的任何应用程序状态也需要重置。对于听起来像您正在搜索的应用程序,没有神奇的“重置”按钮。

一种方法是向Program.cs 添加一个循环,以在“重置”后表单关闭时保持应用运行:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2011-10-29
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多