Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Very Simple C# Asynchronous Timed Message Box

0.00/5 (No votes)
9 Feb 2018 1  
A very simple yet customizable pop-up message box which auto-closes after a specified number of milliseconds.

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
{
    /// <summary>
    /// A timed message box.
    /// </summary>
    /// <remarks>You can change some of the attributes of the underlying text box via the Set method.
    /// <para/>
    /// However, you can access the public TextBox object (as TextBox or tb) directly 
    /// and modify it in your code.
    /// </remarks>
    /// <example>
    /// Definition: static TimedPopUp popUp = new TimedPopUp(); <para />
    /// Usage: popUp.Set("Hello"[, delay][, width][, height][, fontName][, fontSize][, fontStyle]); 
    /// <para />
    /// popUp.Show();
    /// </example>
    partial class TimedPopUp : Form
    {
        public TimedPopUp()
        {
            InitializeComponent();
        }

        public TextBox TextBox { get => tb; }
        static int _waitTime;

        /// <summary>
        /// Initialize the values used to display the message box for a specific number of milliseconds.
        /// </summary>
        /// <param name="msg">The message to display in the text box.</param>
        /// <param name="caption">Optional: The title string of the text box.
        /// Default = "".</param>
        /// <param name="waitTime">Optional: The time to display the message in milliseconds.
        /// Default = 1000.</param>
        /// <param name="width">Optional: The width in pixels of the form.
        /// Default = 600.</param>
        /// <param name="height">Optional: The height in pixels of the form.
        /// Default = 100.</param>
        /// <param name="familyName">Optional: The font family name.
        /// Default = "Courier New".</param>
        /// <param name="emSize">Optional: The size of the font of the text box.
        /// Default = 12.</param>
        /// <param name="style">Optional: The sytyle of the font, viz., 
        /// Regular, Bold, Italic, Underline, or Strikeout.
        /// Default = FontStyle.Bold.</param>
        /// <remarks>Note that the Show method is used to actually display the message box.</remarks>
        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;
        }

        /// <summary>
        /// This is the method which is used to display the message box. 
        /// The Set method must be called prior to using this.
        /// </summary>
        /// <remarks>Note that this method effectively hides the normal Show method for the form.
        /// </remarks>
        async new public void Show()
        {
            // Invoke the normal form Show method to display the message box.
            base.Show();
            // The await operator makes this asynchronous 
            // so that the caller can continue to work while the message is displayed.
            await Task.Delay(_waitTime);
            // Once the wait time has run out the form is hidden.
            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.,

// Use the set method to initialize the settings with 
// non-default values prior to displaying the message. 
p.Set(String.Format("Count: {0}; waiting  for {1} ms.", count.ToString(), wait), 
      "Timed popup", wait, 400,
           style:System.Drawing.FontStyle.Bold);
// The Show method will display the message box for the specified number of milliseconds.
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.,

// The following 2 statements are effectively equivalent. Both will set the backcolor of the message box.
// Note that tb is the name of the textbox on the TimedPopUp form and is public.
p.tb.BackColor = System.Drawing.Color.AliceBlue;
// It can also be referenced more generically as TextBox.
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here