Click here to Skip to main content
15,879,474 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

A Very Simple C# Asynchronous Timed Message Box

Rate me:
Please Sign up or sign in to vote.
4.70/5 (9 votes)
9 Feb 2018CPOL1 min read 35.4K   713   24   9
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

C#
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.,

C#
static TimedPopUp p = new TimedPopUp();

Then, whenever you need to display a message, just invoke p.Set() and then p.Show(), e.g.,

C#
// 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.,

C#
// 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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Takamomto, LLC
United States United States
I have been doing database related programming in the financial services industry for over 20 years on various platforms. I used to be a UNIX Sybase DBA but now prefer programming in the .NET environment using C# and SQL Server.

Comments and Discussions

 
GeneralVery Nice Pin
Jethro195516-Dec-21 2:21
Jethro195516-Dec-21 2:21 
QuestionHide or close the message box? Pin
asiwel26-Mar-18 13:08
professionalasiwel26-Mar-18 13:08 
QuestionHow has anyone given this 5 stars when the code doesn't even exist? Pin
Member 1321046012-Feb-18 21:57
Member 1321046012-Feb-18 21:57 
AnswerRe: How has anyone given this 5 stars when the code doesn't even exist? Pin
Tony Zackin14-Feb-18 16:47
Tony Zackin14-Feb-18 16:47 
QuestionZip file attachment. Pin
Member 1282942012-Feb-18 2:37
Member 1282942012-Feb-18 2:37 
SuggestionA better approach Pin
Nick Polideropoulos10-Feb-18 4:17
Nick Polideropoulos10-Feb-18 4:17 
Hello,
Thanks for the time you spent on this.

As a suggestion on your solution i would say to make the Show method an async Task (called ShowAsync) to make it available for the user able to add continuation tasks around it, to await it and of course to not break the current implementation.

What is your opinion on that?
GeneralRe: A better approach Pin
Tony Zackin14-Feb-18 16:45
Tony Zackin14-Feb-18 16:45 
AnswerRe: A better approach Pin
Nick Polideropoulos15-Feb-18 9:48
Nick Polideropoulos15-Feb-18 9:48 
GeneralRe: A better approach Pin
Bohdan Stupak16-Feb-18 0:46
professionalBohdan Stupak16-Feb-18 0:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.