Introduction
I needed a timed message box for an application I am writing. Rather than reinvent the wheel, I looked around for an existing solution. I found a number of solutions but all were fairly complicated. I knew there had to be a better way so I decided to write it myself.
It turns out that there is a very simple solution which will auto-close a message box after a specified number of milliseconds and is asynchronous to boot.
It is so simple that, rather than describing it, I will just show the annotated code here.
The Code
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace PopUp
{
partial class TimedPopUp : Form
{
public TimedPopUp()
{
InitializeComponent();
}
public TextBox TextBox { get => tb; }
static int _waitTime;
public void Set(string msg, string caption = "",
int waitTime = 1000, int width = 600, int height = 100,
string familyName = "Courier New", float emSize = 12,
FontStyle style = FontStyle.Bold)
{
tb.Text = msg;
tb.Font = new Font(familyName, emSize, style);
this.Size = new Size(width, height);
this.Text = caption;
_waitTime = waitTime;
}
async new public void Show()
{
base.Show();
await Task.Delay(_waitTime);
this.Hide();
}
}
}
How To Use
Included in the zip file is an annotated sample project which demonstrates the usage of the program. Unzip the project. In the project folder, TestAsyncTimedMsgBox, you will see the items TimedPopUp.cs, TimedPopUp.designer.cs, and TimedPopUp.resx. Copy them into your project folder. Then add the form TimedPopUp.cs to your project. Add a reference to the message box form, e.g.,
static TimedPopUp p = new TimedPopUp();
Then, whenever you need to display a message, just invoke p.Set()
and then p.Show()
, e.g.,
p.Set(String.Format("Count: {0}; waiting for {1} ms.", count.ToString(), wait),
"Timed popup", wait, 400,
style:System.Drawing.FontStyle.Bold);
p.Show();
Remarks
You can easily further customize the message box appearance by modifying the Set
method. However, since the textbox, tb
, is defined as public
and is also accessible by the public
property TextBox
, you can directly modify its properties as is done in the included demo program, e.g.,
p.tb.BackColor = System.Drawing.Color.AliceBlue;
p.TextBox.BackColor = System.Drawing.Color.AliceBlue;
Requirements
In order to support the await operator, you must use the .NET Framework 4.5 or above.
History
- Version as of 2/1/18 is 1.0.0.1