Creating a Custom Message Box

Download Source Code

The Windows message box is a sufficient means to display messages to the user. For many applications, the message box will work fine; however, there are times when the message box is limited. For example, suppose you wanted to display a lot of text and therefore wanted a message box that was sizable or even scrollable by the user. There are also times when you might develop an application with a great user interface but it is ruined by the dull Windows message box.

Fortunately, it is very easy for C# developers to develop a custom message box of their own to incorporate it into their applications. In this article, I will explain how to create a simple OK/Cancel message box. I will also improve on the message box by adding a timer feature.

You're now going to create a custom message box. Create a new Windows Application titled MyMessageBox. Use the following table to set the properties for the form.

Property Value
Size 400,150
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen

Place two buttons on the form. Use the following table to set the properties for button1.

Property Value
Name btnOk
Location 217,86
Size 84,27
Text OK

Now, use the following table to set the properties for button2.

Property Value
Name btnCancel
Location 307,86
Size 84,27
Text Cancel

Finally. place a label on the form. Use the following table to set the properties for label1.

Property Value
Name lblMessage
Location 9,7

The Code

The code for the custom message box is quite simple. First, you need to declare a variable called Button_id; this variable will hold a number—either 1 or 2. If the user clicks the OK button, this variable will be set to 1; if the user clicks the Cancel button, the variable will be set to 2. This variable will be used to determine which button was clicked. The variable is declared as type string and is a static variable.

You also need to define an object of MyMessageBox; it is also defined as static. Both should be declared just under the public partial class:

static MyMessageBox newMessageBox;
static string Button_id;

The Windows C# MessageBox Class has a Show() method. For your custom message box, you will create a ShowBox() method that will be an overloaded method. This overloaded method will take one or two parameters. This method also will be used as an Accessor. This means that not only can you use the method to set the message on our message box but you also can get a result back. Thats is, you can determine which button was clicked by the user (OK/Cancel). Following is the code for the ShowBox() method.

public static string ShowBox(string txtMessage)
{
   newMessageBox = new MyMessageBox();
   newMessageBox.label1.Text = txtMessage;
   newMessageBox.ShowDialog();
   return Button_id;
}

The preceding is the first of the two overloaded ShowBox() methods. It takes one parameter; this parametter is the message to be displayed on your message box. Previously, you defined an ojbect 'newMessageBox' from your MyMessageBox class; now, in the ShowBox() method, you use the new keyword to instaniate the object.

Now that an object of MyMessageBox Class is created, you can set the label of the message box. After setting the message, you need to show the message box; you use the ShowDialog() method to show the message box as a dialog box. This means that when your message box is displayed, the user will not be able to interact with the form that created the message box until the user makes a choice—either OK, Cancel, or the X Close button.

Finally, you use the return statement to return a value back to the calling method. This value, as mentioned earlier, is either 1, 2, or null if the X button is clicked.

The second overloaded method of the ShowBox() method takes two parameters. The first is the message; the second is the title. The title is used to set the message box's title. If the ShowBox() method is used with only one parameter, the message box's title will be that of the Class name unless changed.

Finally, you need to code both the OK and Cancel buttons. The code behind these two buttons is very simple. Both the bottoms need to dispose of the message box; however, before they dispose of the message box, they both need to store a value in the Button_id variable. After storing a value into the variable, the message box then is disposed of and execution returns to the calling method. The value stored in the Button_id variable is also returned. This will allow the user to preform some processing. The complete code follows.

static MyMessageBox newMessageBox;
static string Button_id;

public static string ShowBox(string txtMessage)
{
   newMessageBox = new MyMessageBox();
   newMessageBox.label1.Text = txtMessage;
   newMessageBox.ShowDialog();
   return Button_id;
}

public static string ShowBox(string txtMessage, string txtTitle)
{
   newMessageBox             = new MyMessageBox();
   newMessageBox.label1.Text = txtMessage;
   newMessageBox.Text        = txtTitle;
   newMessageBox.ShowDialog();
   return Button_id;
}

private void btnOk_Click(object sender, EventArgs e)
{
   Button_id = "1";
   newMessageBox.Dispose();
}

private void btnCancel_Click(object sender, EventArgs e)
{
   newMessageBox.Dispose();
   Button_id = "2";
}

Creating a Custom Message Box

How to Use the Message Box

Following are examples of how to use the custom message box.

Example 1

MyMessageBox.ShowBox("Do you want to exit?");

Example 2

MyMessageBox.ShowBox("Do you want to exit?", "Exit");

Example 3

string btnClicked = MyMessageBox.ShowBox("Do you want to exit?");

if (btnClicked == "1")
{
   // User clicked OK button. Do some processing.
}
else
{
   // User clicked Cancel button. Do some processing.
}

Notice in the these examples that you do not need to create an instance of the message box class. This is done in the ShowBox() method. In this article, I have explained how to make a simple OK/Cancel MessageBox. However, the C# MessageBox Class has many overloaded Show() methods and many types of message box's, such as Yes/No; you also can set the message box icon. By adding a few more overloaded ShowBox() methods, you also can cater for the message box type such as Yes/No or Ok/Cancel and even add a message box icon but that is not covered in this article. Please remember that this is only a simple example meant to give you an insight into how to create a custom message box.

Adding A Timer Feature

You can expand your custom message box by adding a timer that will count down from a value and then dispose of the message box if the user has not made a choice. To achieve this, you need a variable that will hold a value and create a timer that will decrement the value from the variable. Begin by adding a label to the message box; this message will display the timer value decrementing. Place a new label on the form and use the following table to set the label2 properties.

Property Value
Name lblTimer
Location 9,100

You need to declare a new variable that will hold the decrementing timer value; the variable should be of type int. See the following code fragment.

static MyMessageBox newMessageBox;
static string Button_id;
int disposeFormTimer;

The next step is to create a timer. Rather than using the timer from the toolbox, you will create a new timer object yourself. The timer object should be created in the MyMessageBox_load event. See the following code fragment.

private void MyMessageBox_Load(object sender, EventArgs e)
{
   disposeFormTimer  = 30;
   Timer msgTimer    = new Timer();
   msgTimer.Interval = 1000;
   msgTimer.Enabled  = true;
   msgTimer.Start();
   msgTimer.Tick += new System.EventHandler(this.timer_tick);
}

The preceding code is fairly simple. You store the value 30 in the disposeFormTimer variable. The timer object then will decrement from this value. You add a Tick event to the msgTimer timer object. This event name is timer_tick; this event gets triggered every second. Finally, you need to code the timer_tick event. This event will simply decrement from the value stored in the disposeFormTimer variable and update the lblTimer label with the decrementing value. Following is the code frangment for the timer_tick event.

private void timer_tick(object sender, EventArgs e)
{
   disposeFormTimer--;

   if (disposeFormTimer >= 0)
   {
      newMessageBox.lblTimer.Text = disposeFormTimer.ToString();
   }
   else
   {
      newMessageBox.Dispose();
   }
}

The if statement checks the value of disposeFormTimer variable. If it is greater or equal to zero, lblTimer label will update with the new value stored in disposeFormTimer. Once the value in disposeFormTimer variable is below zero, the message box will use the dispose() method to close.

By adding a timer to our message box, you have given it an extra feature that the C# MessageBox Class does not have. Remember, the point of making a custom message box is to either add new features or improve the UI of the messagebox.



Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Webinar on September 23, 2014, 2 p.m. ET / 11 a.m. PT Mobile commerce presents an array of opportunities for any business -- from connecting with your customers through mobile apps to enriching operations with mobile enterprise solutions. Join guest speaker, Michael Facemire, Forrester Research, Inc. Principal Analyst, as he discusses the new demands of mobile engagement and how application program interfaces (APIs) play a crucial role. Check out this upcoming webinar to learn about the new set of …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds