C# Winforms - 使用 FormClosing 时,消息框未在 if 语句中打开

问题描述 投票:0回答:1

我试图在按下表单上的“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) {; }

知道为什么会发生这种情况吗?

c# messagebox formclosing
1个回答
0
投票

此错误是由计时器和后台工作程序引起的,它们在

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();
    }
}

...
© www.soinside.com 2019 - 2024. All rights reserved.