0

我有一个 MessageBox.Show 事件,我还想阻止基于计时器的方法在 MessageBox 保持打开状态时运行。

这是我的代码(每 x 分钟更改一次网络上文件位置的值):

public void offlineSetTurn()
{
    try
    {
        using (StreamWriter sWriter = new StreamWriter("FileLocation"))
        {
            sWriter.WriteLine(Variable);
        }
    }
    catch (Exception ex)
    {
        DialogResult result = MessageBox.Show("Can't find file.  Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);

        if (result == DialogResult.OK)
        {
            offlineSetTurn();
        }
        else if (result == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }
}

我有每三十秒调用一次的方法。这意味着每隔三十秒,就会弹出另一个 MessageBox。有没有办法使用 MessageBox 暂停应用程序,如果没有,解决此问题的最佳方法是什么?如果可能的话,我想避免使用 Timer.Stop() 因为它会重置计时器计数。

4

1 回答 1

1

最简单的解决方案是设置一个标志来指示消息框当前是否打开:

private bool isMessageBoxOpen = false;

public void offlineSetTurn()
{
    if (isMessageBoxOpen)
        return;

    try
    {
        using (StreamWriter sWriter = new StreamWriter("FileLocation"))
        {
            sWriter.WriteLine(Variable);
        }
    }
    catch (Exception ex)
    {
        isMessageBoxOpen = true;
        DialogResult result = MessageBox.Show("Can't find file.  Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);
        isMessageBoxOpen = false;

        if (result == DialogResult.OK)
        {
            offlineSetTurn();
        }
        else if (result == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }
}
于 2011-08-25T03:08:35.597 回答