0

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.

Omniabsence
  • 171
  • 1
  • 3
  • 13
  • I think the easiest solution is to have a second non-modal window that can spool messages from the first. The depending on the user input in the second window, you can exit or call `offlineSetTurn()`. – Nithin Philips Aug 25 '11 at 03:03
  • Ah that makes sense. Such as adding a second bool canConnect() method that calls my aforementioned offlineSetTurn() method only when canConnect() returns true? – Omniabsence Aug 25 '11 at 03:09

1 Answers1

1

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();
        }
    }
}
ChrisWue
  • 18,612
  • 4
  • 58
  • 83