C# 关闭和重新打开表单而不关闭应用程序
我正在尝试重置我的主窗体,以便可以轻松重置所有文本框和变量。我在Progam.cs中添加了一个bool,以使应用程序在表单关闭然后重新打开时保持打开状态。当我试图关闭它时,on_closing甚至会触发两次。我不知道该怎么做才能阻止它发生,但我知道这必须是简单的事情 Program.cs:C# 关闭和重新打开表单而不关闭应用程序,c#,winforms,reset,C#,Winforms,Reset,我正在尝试重置我的主窗体,以便可以轻松重置所有文本框和变量。我在Progam.cs中添加了一个bool,以使应用程序在表单关闭然后重新打开时保持打开状态。当我试图关闭它时,on_closing甚至会触发两次。我不知道该怎么做才能阻止它发生,但我知道这必须是简单的事情 Program.cs: static class Program { public static bool KeepRunning { get; set; } /// <summary> ///
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());
}
}
}
删除
应用程序。退出()
。由于您已经在FormClosing事件处理程序中,如果程序.KeepRunning
设置为false,应用程序将退出。这是因为您调用了Application.exit()。由于您的表单尚未关闭,如果您尝试关闭应用程序,该指令将首先尝试关闭表单,然后再调用事件处理程序
另外,我认为您不需要Application.Exit(),因为这是您唯一的表单,因此应用程序将自动关闭(至少在我的VB6旧版本中是这样!)如果我这样做,然后单击“否”,它将永远不会关闭。在您反复单击“否”后,它会重新打开。我更新了我的答案,因为我向FastThank读了一点您的问题。谢谢。这就是问题所在,现在它有意义了。@HansPassant,我想说这肯定不是重复,很可能是另一个重复综合征病例。即使解决方案是相同的,这些问题也是不同的。“关闭表单而不关闭应用程序”,完全相同的问题。
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");
}
}