Search code examples
c#winformstimermessageboxauto-close

Open multiple instances of MessageBox and automatically close after several seconds


I am coding Windows Forms in C# under Visual Studio 2012 and I would like to open multiple instances of MessageBox and automatically close them after several seconds.

I have found (and upvoted) this answer here: SO: Close a MessageBox after several seconds.

However, this works if I only open 1 (one) MessageBox at a time, since it makes use of the function FindWindow, and the multiple instances of my MessageBox shall have all the same window title (caption).

[Optionally] In addition, I would like to present the user with a countdown, like This dialog will close in 5 seconds, This [...] in 4 seconds, This [...] in 3 seconds, ..., This [...] in 1 seconds and then finally close the MessageBox.

Is there a way to uniquely reference my multiple MessageBoxes and automatically close them (either using System.Timers.Timer or System.Threading.Timer or System.Windows.Forms.Timer - whichever is the best fit for this solution) after a certain period of time (say 5 seconds)?


Solution

  • I suggest not using a MessageBox for this task. Instead, make your own custom form. Make it the size, shape, and look you want. Then, in its code-behind file, you can create a timer, unique to that window itself. That way, you can spawn as many of them as you want, and they will manage their own timers and closing themselves, and you don't have to do anything like finding the window. It's possible to make a Form look very much like a MessageBox. And because you can call ShowDialog, you can make them behave similarly to MessageBoxes as well (though that would be somewhat counterproductive, because you can only interact with one dialog at a time).