关闭并重新打开表单而不关闭应用程序

时间:2013-03-24 00:49:09

标签: c# winforms reset

我正在尝试重置我的主窗体,以便我可以轻松地重置所有文本框和变量。我已经在我的Progam.cs中添加了一个bool,以便在窗体关闭然后重新打开时使应用程序保持打开状态。当我试图关闭它时,on_closing甚至会发射两次。我不知道如何阻止它发生,但我知道它必须是简单的。

的Program.cs:

static class Program
{
    public static bool KeepRunning { get; set; }
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        KeepRunning = true;
        while (KeepRunning)
        {
            KeepRunning = false;
            Application.Run(new Form1());
        }

    }
}

Form1中:

private void button1_Click(object sender, EventArgs e)
    {
        Program.KeepRunning = true;
        this.Close();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("You have unsaved work! Save before closing?", "Save?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
        if (dialogResult == DialogResult.Yes)
        {
            e.Cancel = true;
            MessageBox.Show("saving then closing");
            Application.Exit();
        }

        if (dialogResult == DialogResult.No)
        {
            MessageBox.Show("closing");
            Application.Exit();
        }

        if (dialogResult == DialogResult.Cancel)
        {
            e.Cancel = true;
            MessageBox.Show("canceling");
        }
    }

2 个答案:

答案 0 :(得分:0)

删除Application.Exit()。由于您已经在FormClosing事件处理程序中,因此如果Program.KeepRunning设置为false,则应用程序将退出。

答案 1 :(得分:0)

这是因为您调用Application.Exit()。由于您的表单尚未关闭,如果您尝试关闭该应用程序,该指令将尝试关闭表单拳头,反过来,它将再次调用事件处理程序。

另外,我认为你不需要Application.Exit(),因为这是你唯一的表格,因此应用程序将自动关闭(至少那是我以前在VB6中发生的事情!)

相关问题