我试图在按下表单上的“x”按钮时打开消息框;仅当满足特定条件时。我有以下代码:
bool uncommitted = false;
// Do something which sets uncommitted to true
...
// If uncommitted, open message box
if (uncommitted)
{
result = MessageBox.Show("Are you sure you want to exit?", "Testing",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (result == DialogResult.No)
e.Cancel = true;
}
编译完成后,当表单关闭时,表单会冻结并且鼠标光标加载圆圈出现。
如果我将消息框代码放在 if 语句之外,则消息框将按预期打开。
// This code opens the message box without any regard to the condition
...
result = MessageBox.Show("Are you sure you want to exit?", "Testing",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (result == DialogResult.No)
e.Cancel = true;
if (uncommitted) {; }
知道为什么会发生这种情况吗?
此错误是由计时器和后台工作程序引起的,它们在
FormClosing()
时仍在运行。在调用 MessageBox.Show()
函数之前关闭这些进程解决了问题:
...
// Close processes
if (timer.enabled) timer.Stop();
if (backgroundWorker.IsBusy) backgroundworker.CancelAsync();
// Some code to determine state of uncommitted
...
// Open messagebox
if (uncommitted)
{
result = MessageBox.Show("Are you sure you want to exit?", "Test",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (result == DialogResult.No)
{
e.Cancel = true;
timer.Start();
backgroundWorker.RunWorkerAsync();
}
}
...