MDI 窗体中的消息框在应用程序关闭之前多次显示
本文关键字:显示 应用程序 窗体 消息 MDI | 更新日期: 2023-09-27 17:56:26
我知道即使在StackOverflow中也有类似问题的例子,但我很难理解问题的本质,因此很难解决我的自定义情况。
我现在拥有的是这段代码:
bool closingPending = false;
private void MyFormN_FormClosing(object sender, FormClosingEventArgs e)
{
if (closingPending) return;
//DialogResult answer = MessageBox.Show("Do you want to save changes ?", "Save",
if (MessageBox.Show("Do you want to save changes ?", "Save",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button3) == DialogResult.Yes)
{
closingPending = true;
MessageBox.Show("To Do - validate and save");
}
if (MessageBox.Show("Do you want to save changes ?", "Save",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button3) == DialogResult.Cancel)
{
closingPending = true;
e.Cancel = true;
}
if (MessageBox.Show("Do you want to save changes ?", "Save",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button3) == DialogResult.No)
{
closingPending = true;
Application.Exit();
}
}
这是我的尝试和我从这里其他帖子中获得的一些想法的结果。但是当我执行此代码时发生的情况是 - 通过按窗口的[x]
,我会显示消息框,但无论我单击哪个按钮,表单都会显示几次。在添加closingPending
之前,我很确定此问题仅在我尝试Application.Exit()
时才发生。当我尝试此示例时,closingPending
示例有效:
if(closingPending) return;
if (MessageBox.Show("This application is closing down because of " + e.CloseReason.ToString() + ". Do you really want to close it ?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
else
{
closingPending = true;
Application.Exit();
}
但是,我对导致问题的原因有一些想法,但我离完全理解或解决它还很远。
尝试如下...它将解决您的问题。
DialogResult result = MessageBox.Show("Do you want to save changes ?", "Save",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button3);
switch (result)
{
case DialogResult.Yes:
closingPending = true;
MessageBox.Show("To Do - validate and save");
break;
case DialogResult.No:
closingPending = true;
Application.Exit();
break;
case DialogResult.Cancel:
closingPending = true;
e.Cancel = true;
break;
}