Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#

A Custom Message Box

Rate me:
Please Sign up or sign in to vote.
3.46/5 (39 votes)
2 Aug 2013CPOL7 min read 469K   32.7K   107   65
This article explains how to develop a custom message box in C#.

Dear all,
My sincere appologies to you all for visiting the broken link. I have been away from CP for a while and from personal projects. I did not renew the website and as a result I lost ownership. Once again, I'd like to appologie for those who visited the direct link. I am truly sorry.

Version 1

Image 1

Version 2

Image 2

Update

This article explains how Version 1 was developed. I have since updated the sample project. Features in the new updated version include:  

  • MessageBox icons.
  • Expandable form to accommodate longer text.
  • Three animation styles (SlideDown, FadeIn, and ZoomIn).
  • MessageBox beep sound. 
  • Returns a DialogResult object when button is clicked.
  • New interface.   

Introduction

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 want to display a lot of text and therefore want 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 make some suggestions on how you can 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. Set the properties for the form using the table below.

PropertyValue
Size400,150
FormBorderStyleFixedToolWindow
ShowInTaskBarFalse
StartPositionCenterScreen

Place two buttons on the form. Set the properties for button1 using the table below:

PropertyValue
NamebtnOk
Location217, 86
Size84,27
TextOK

Now set the properties for button2 using the table below.

PropertyValue
NamebtnCancel
Location307, 86
Size84,27
TextCancel

Finally place a Label on the form. Set the properties for label1 using the table below.

PropertyValue
NamelblMessage
Location9,7

The Code

The code for the custom message box is quite simple. First we 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 and 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.

We also need to define an object of MyMessageBox which is also defined as static. Both should be declared just under public partial class...

C#
static MyMessageBox newMessageBox;
static string Button_id;

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

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

Above is the first of the two overloaded ShowBox() method. It takes one parameter, this parameter is the message to be displayed on our message box. Previously we defined an object newMessageBox from our MyMessageBox class, now in the ShowBox() method we instantiated the object using the new keyword.

Now that an object of MyMessageBox class is created, we can set the label of the message box. After setting the message we need to show the message box, we use the method ShowDialog() to show the message box as a dialog box. This means when our 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 we use the return statement to return a value back to the calling method. This value as mentioned above 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 and 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 then the message box's title will be that of the class name unless changed.

Finally we 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 is then disposed of and execution returns to the calling method. The value stored in the variable Button_id is also returned. This will allow the user to perform some processing. Below is the complete code.

C#
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"; 
}

How to use the Message Box

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

Example 1

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

Example 2

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

Example 3

C#
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 examples above 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 and you can also set the message box icon. By adding a few more overloaded ShowBox() methods you can also 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

We can expand on our 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 we need a variable which will hold a value and create a timer which will decrement the value from the variable. Let's begin by adding a label to the message box which will display the timer value decrementing. Place a new label on the form and set the label2 properties using the table below.

PropertyValue
NamelblTimer
Location9, 100

We need to declare a new variable which will hold the decrementing timer value, the variable should be of type int. See the code fragment below.

C#
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 we will create a new timer object our self. The timer object should be created in the MyMessageBox_load event. See the code fragment below.

C#
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 code above is fairly simple. We store the value 30 in the variable disposeFormTimer. The timer object will then decrement from this value. We add a Tick event to the msgTimer timer object. This event name is timer_tick, this event gets triggered every second. Finally we 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. Below is the code fragment for the timer_tick event.

C#
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 then lblTimer label will update with the new value stored in disposeFormTimer. Once the value in disposeFormTimer variable is below zero the message box will close using the dispose() method.

By adding a timer to our message box we have given it an extra feature which 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCorrupted zip file in version 1 Pin
parmando10-Nov-22 14:18
parmando10-Nov-22 14:18 
BugInvisible window Pin
Member 1381510728-Apr-21 5:31
Member 1381510728-Apr-21 5:31 
Questiondownload is broken again. Pin
Member 139810571-Mar-19 3:43
Member 139810571-Mar-19 3:43 
QuestionApplication deadlock if a breakpoint is set in Pin
ROY Jean10-Feb-19 1:21
ROY Jean10-Feb-19 1:21 
QuestionWARNING WARNING WARNING!!!!! Pin
TheMattster13-Jul-17 9:36
TheMattster13-Jul-17 9:36 
AnswerRe: WARNING WARNING WARNING!!!!! Pin
OriginalGriff13-Jul-17 9:39
mveOriginalGriff13-Jul-17 9:39 
GeneralRe: WARNING WARNING WARNING!!!!! Pin
Sean Ewington13-Jul-17 9:42
staffSean Ewington13-Jul-17 9:42 
GeneralRe: WARNING WARNING WARNING!!!!! Pin
OriginalGriff13-Jul-17 9:52
mveOriginalGriff13-Jul-17 9:52 
GeneralCode is great, but watch out for that direct code link! Pin
Michaela Joy22-Nov-16 8:01
Michaela Joy22-Nov-16 8:01 
GeneralMy vote of 1 Pin
Member 80212104-Nov-16 4:11
Member 80212104-Nov-16 4:11 
GeneralRe: My vote of 1 Pin
OriginalGriff4-Nov-16 4:13
mveOriginalGriff4-Nov-16 4:13 
GeneralRe: My vote of 1 Pin
Member 80212104-Nov-16 4:28
Member 80212104-Nov-16 4:28 
GeneralRe: My vote of 1 Pin
OriginalGriff4-Nov-16 4:39
mveOriginalGriff4-Nov-16 4:39 
GeneralRe: My vote of 1 Pin
Sean Ewington4-Nov-16 4:46
staffSean Ewington4-Nov-16 4:46 
QuestionDefault Button in VB.Net version Pin
SumitSaha31-Oct-15 18:25
SumitSaha31-Oct-15 18:25 
Questionits very good Pin
javadtoosi2-Aug-15 6:56
javadtoosi2-Aug-15 6:56 
QuestionHow Can I Make Version 2 of this message box as a complete component Pin
Member 113831504-Feb-15 4:24
Member 113831504-Feb-15 4:24 
QuestionEnvironment.NewLine Pin
burgo8558-Dec-14 23:01
burgo8558-Dec-14 23:01 
Questionhello Pin
mouse7112-Jul-14 17:54
mouse7112-Jul-14 17:54 
AnswerRe: hello Pin
Yang Kok Wah2-Jul-14 20:32
Yang Kok Wah2-Jul-14 20:32 
GeneralRe: hello Pin
mouse7117-Jul-14 15:43
mouse7117-Jul-14 15:43 
GeneralRe: hello Pin
Syed M Hussain9-Jul-14 6:57
Syed M Hussain9-Jul-14 6:57 
GeneralRe: hello Pin
mouse71113-Jul-14 16:49
mouse71113-Jul-14 16:49 
QuestionDialogResult enum Pin
Maria Hdez.17-Jun-14 7:21
professionalMaria Hdez.17-Jun-14 7:21 
AnswerRe: DialogResult enum Pin
Syed M Hussain17-Jun-14 8:05
Syed M Hussain17-Jun-14 8:05 

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.