关闭并重新打开表单而不关闭应用程序
我想重置我的主表单,以便我可以轻松地重置所有文本框和变量。我在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");
}
}
删除您Application.Exit()
。由于您已经在FormClosing事件处理程序中,因此如果Program.KeepRunning
设置为false,则应用程序将退出。
如果我这样做,然后点击否,它永远不会关闭。它只是重复打开后,你不反复点击。 – 2013-03-24 01:32:04
我更新了我的答案,因为我读了你的问题一点点快速 – darthmaim 2013-03-24 01:34:56
非常感谢,现在它是有道理的。 – 2013-03-24 01:40:59
发生这种情况是因为您调用了Application.Exit()。由于您的表单尚未关闭,如果您尝试关闭应用程序,那么该指令将尝试关闭表单拳头,然后再次调用事件处理程序。
另外,我不认为你需要Application.Exit(),因为这是你的唯一形式和应用,因此会自动关闭(至少这是我的VB6发生了什么事,人杰地灵!)
@HansPassant ,我想说这肯定不是重复的,很可能是另一个重复的综合征病例。即使解决方案是相同的,这些问题也是不同的。 – 2013-03-24 01:48:19
“关闭表单而不关闭应用程序”,完全相同的问题。 – 2013-03-24 01:51:27