C#创建程序,FormClosing事件执行两次

Creating program in C#, FormClosing event executes twice

正如我在标题中所说,我正在创建一个程序。但是,我面临 FormClosing 事件执行两次的问题。出现消息框并且按钮很好地发挥了它们的作用,但是当我单击 "Yes" 或 "No" 时,它会自己重复。幸运的是 "Cancel" 按钮没有这个问题。

private void Form1_FormClosing (object sender, FormClosingEventArgs e)
{
    DialogResult dialog = MessageBox.Show("Do you want to save your progress?", "Media Cataloguer", MessageBoxButtons.YesNoCancel);

    if (dialog == DialogResult.Yes)
    {
        SaveFileDialog savefile = new SaveFileDialog();
        savefile.Filter = "Text files|*.txt";
        savefile.Title = "Save As";
        savefile.ShowDialog();
        System.IO.FileStream fs = (System.IO.FileStream)savefile.OpenFile();
        Application.Exit();
    }
    else if (dialog == DialogResult.No)
    {
        MessageBox.Show("Are you sure?", "Media Cataloguer", MessageBoxButtons.YesNo);
        Application.Exit();
    }
    else if (dialog == DialogResult.Cancel)
    {
        e.Cancel = true;
    }
}

我发现没有其他任何东西对我有很大帮助。正如我之前所说,消息框出现了两次。这是我唯一的问题。此空白的其他所有内容都可以正常工作。

您的第二个 MessageBox 没有意义,您不必退出应用程序。
如果不将 e.Cancel 设置为 true,window 应该关闭:
https://msdn.microsoft.com/en-us/library/system.windows.window.closing%28v=vs.110%29.aspx

private void Form1_FormClosing (object sender, FormClosingEventArgs e) {
    DialogResult dialog = MessageBox.Show("Do you want to save your progress?", "Media Cataloguer", MessageBoxButtons.YesNoCancel);

    if (dialog == DialogResult.Yes) {
        SaveFileDialog savefile = new SaveFileDialog();
        savefile.Filter = "Text files|*.txt";
        savefile.Title = "Save As";
        savefile.ShowDialog();
        System.IO.FileStream fs = (System.IO.FileStream)savefile.OpenFile();
    } else if (dialog == DialogResult.No) {
        if(MessageBox.Show("Are you sure?", "Media Cataloguer", MessageBoxButtons.YesNo) == DialogResult.No){
           e.Cancel = true;
        }
    } else if (dialog == DialogResult.Cancel) {
        e.Cancel = true;
    }
}

我不会在 window 关闭事件中退出该应用程序。
它不是为执行该任务而设计的。
您可以使用 项目设置来定义应用程序何时退出
或者,如果您需要 更多控制,您可能希望在 App.cs 中处理它。
但我不会在这里做。

您的问题是您正在调用 Application.Exit()。作为MSDN says,

The Exit method stops all running message loops on all threads and closes all windows of the application

换句话说,它将再次触发表单关闭事件。

要解决这个问题,请改用 Environment.Exit(0)

您真的不应该向用户抛出超过一个消息框...您可能需要阅读 this, this, and this。也就是说,我考虑退出并提示保存为一个人的好地方之一,但不是两个人。

您已经设置了正确的机制(他们可以回答是、否或取消)。修改您的问题以使用户更清楚:"Would you like to save your work before exiting?" 如果他们取消,则像您使用的那样取消 e.Cancel。否则,只需让表单自行关闭即可。

如果他们回答否,请不要再问。我现在可以听到他们...

"I already told you, just EXIT!!!"