0

How can I open a MessageBox , keep it open until a task finishes, and then close it.

I plan to insert a loading animation inside it.

I need to somehow make it that you cannot close it by clicking it, just through the code.

var t = Task.Run(() =>
{
    MessageBox.Show("Loading!");

    CycleValue = 0;
    while (CycleValue < noOfCycles && buttonStartStop.Text == "Stop")
    {
        this.Invoke((MethodInvoker)delegate
        {
            gm.NextState();
            CycleValue++;
            if (CycleValue == noOfCycles)
            {
                buttonStartStop.Text = "Start";
                buttonRandomise.Enabled = true;
                buttonReset.Enabled = true;
            }
        });
    }
});
dhilmathy
  • 2,800
  • 2
  • 21
  • 29
extra8
  • 67
  • 11
  • What code have you tried thus far? – Becuzz Jul 12 '18 at 20:53
  • 1
    What you describe is a *modal* dialog or message box, if that helps. – Shelby115 Jul 12 '18 at 20:55
  • A message box in WinForms won't be able to do what you want. You'll need to open a new frame or modal dialog. – damian Jul 12 '18 at 20:57
  • Modal seems wrong for this unless the goal is to block access to the rest of the UI. To stop users from closing you'd intercept close, quit, cancel messages and discard them, and have the worker task PostMessage some other custom message on completion. – Dave S Jul 12 '18 at 21:01
  • Added part of the code. In the while loop some values are going to get changed and be displayed. While that is happening I want something that opens and restricts access to the main form. – extra8 Jul 12 '18 at 21:02
  • A custom model dialog would allow that. Again, intercept / handle the "stock" close messages without calling the base class, while having a custom private close message to call from your task. – Dave S Jul 12 '18 at 21:03

2 Answers2

2

You need to create your own form/window that mimicks the look of the message box, but that you have more control over (eg implementing a closing event after a task has completed). A label and a couple of buttons shouldn't take too long, and will be useful in future projects!

  • @extra8 You should have your working code inside this custom window, so you can show that Form as Modal without problems. If you need more control over the animation (if you are going to use a Gif or a Png as animation), take a look at this .Net class: [ImageAnimator](https://msdn.microsoft.com/en-us/library/system.drawing.imageanimator(v=vs.110).aspx?f=255&MSPPError=-2147217396&cs-save-lang=1&cs-lang=csharp#code-snippet-1). – Jimi Jul 12 '18 at 21:55
0

IF you want to show the busy cursor while an action is being performed on UI you can use -

 Cursor.Current = Cursors.WaitCursor;

If you want to show an animation refer this

Gaurav Jalan
  • 467
  • 2
  • 14