Question

I have a MessageBox.Show event that I want to also prevents timer-based methods from running while the MessageBox remains open.

Here is my code (Changes the value in a file location on a network every x minutes):

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

I have methods in the form that are calling this every thirty seconds. Meaning every thirty seconds, another MessageBox pops up. Is there a way to pause the application with MessageBox and if not, what would be the best way to resolve this issue? If possible, I'd like to avoid using Timer.Stop() as it would reset the Timer count.

Was it helpful?

Solution

The simplest solution is to have a flag indicating whether or not the message box is currently open:

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();
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top