0

I want to use a MessageBox in a while loop with OK button. I want the MessageBox keeps showing until the user presses OK button. If I use this code the box shows up and it waits until the user presses the button and it does not proceed to the next iteration.

DialogResult dialogResult;
StopIteration = false;
While(!StopIteration)
{
   nIteration += 1;
   dialogResult = MessageBox.Show(string.Format("Iteration: {0}", nIteration), "Iterations", MessageBoxButtons.OK);
    if (dialogResult == DialogResult.OK)
    {
        StopIteration = true;
    }
}   

Alternatively I made a form with a label to be modified during the loop:

public partial class RunMessageBox : Form
{
   public RunMessageBox()
   {
        InitializeComponent();
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   }
}

RunMessageBox runMessageBox = new RunMessageBox();
runMessageBox.Show(); // If I use DialogShow instead the same problem as MessageBox happens
While(!StopIteration)
{
    nIteration += 1;
    runMessageBox.labelIteration.Text = string.Format("Iteration: {0}", nIteration);

    if (runMessageBox.checkBoxStopIteration.Checked)
                {
                    StopIteration = true;
                }
}

This time the label and check box for stopping are not displayed until the last iteration (the code includes maximum iteration check).

Meisam
  • 1
  • 1
  • 2
    "I want the MessageBox keeps showing until the user presses OK button" - you don't need a loop for that. – Dai Oct 23 '20 at 13:57
  • 1
    What problem are you facing, exactly? Your posting doesn't seem to contain an actual question or problem-description. – Dai Oct 23 '20 at 13:57
  • 1
    It sounds like you want to run a cancelable task in the background - in which case you should use `Task.Run` and `TaskCancellationSource`. – Dai Oct 23 '20 at 13:58
  • I want to run a loop showing the text box and the loop stops when the user presses a button. – Meisam Oct 23 '20 at 14:02
  • "I want to run a loop showing the text box" - I think you misunderstand how loops work in GUI programs. A synchronous loop is not able to "show" anything because the loop *has to break* in order to return to the window-message-pump, otherwise your program will freeze and be unresponsive. You should read this: https://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows – Dai Oct 23 '20 at 14:03
  • I just saw the concept of asynchronous programming. I will read about it, thanks! – Meisam Oct 23 '20 at 14:09

0 Answers0