Click here to Skip to main content
Click here to Skip to main content

A customizable .NET WinForms Message Box

, 26 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A customizable .NET WinForms message box with three buttons, custom icon, and checkbox.

Introduction

When I do .NET WinForms programming, I often need a message box with different options. .NET offers the MessageBox.Show() API which shows a standard Windows message box. The Windows message box has very limited button combinations (like OK-Cancel, Yes-No, and a few more). I needed a message box with customizable button captions (like Install-Don't Install or Send Error Report-Don't Send). Also, it would be nice to have a "Don't show this message again" checkbox. So I developed a message box Form (derived from Form) which would allow me all that and I thought I'd share it.

I used this API when developing StresStimulus, a free Fiddler extension for load testing web applications.

Features

  • 1-3 buttons with custom captions.
  • Optional checkbox with custom text.
  • Optional icon. Either a standard Windows icon or any custom icon.
  • Custom dimensions of the message box.

Constructors

The message box comes with three constructors. The simplest one takes the message box text and title. The message can be any length and width because the message box stretches to fit the text. To show the message box, call the ShowDialog(this) method.

MsgBox db = new MsgBox("This is a test message", "This is a test title");
db.ShowDialog(this); //show the message box.

To add an icon to the top left corner, use one of the two other constructors. You can either provide a standard Windows icon using the System.Windows.Forms.MessageBoxIcon enumeration or any custom icon object. You can also get a standard Windows icon object through the System.Drawing.SystemIcons class.

//Using the MessageBoxIcon enum. 
MsgBox db = new MsgBox("This is a test message", 
            "This is a test title", MessageBoxIcon.Information);
db.ShowDialog(this); //show the message box.

//Using the System.Drawing.SystemIcons class.
MsgBox db = new MsgBox("This is a test message", 
            "This is a test title", SystemIcons.Information);
db.ShowDialog(this); //show the message box.

Button setup

The message box comes with 1-3 buttons, each with a DialogResult value. Buttons are customized using the SetButtons method. By default, if this method is not called, then an OK button is created. This method is overloaded. The simplest one takes String[] button captions (the string array must have a length between 1 and 3). These buttons will have a DialogResult value DialogResult.None. To determine which button was clicked, you can use the DialogBoxResult property.

//Sets 2 buttons with DialogResult.None.
MsgBox db = new MsgBox("This is a test message", 
                "This is a test title", 
                MessageBoxIcon.Information);
db.SetButtons("First Button", "Second Button");
db.ShowDialog(this); //show the message box. Does not return a DialogResult value.
//Returns what button was pressed. DialogBoxResult.Button1 or DialogBoxResult.Button2
DialogBoxResult result = db.DialogBoxResult;

Another variation also takes DialogResult[] that assigns a DialogResult value to a button (the array must be the same length as captions) and the default button number (must be 1-3). To determine which button was clicked, DialogResult is returned from ShowDialog(this).

//Sets 2 buttons with DialogResult.None.
MsgBox db = new MsgBox("This is a test message", 
            "This is a test title", MessageBoxIcon.Information);
//by default the second button will be selected.
db.SetButtons(new string[]{"Yes Button.", "No Button"}, 
              new DialogResult[] {DialogResult.Yes, DialogResult.No}, 2);
DialogResult r = db.ShowDialog(this); //show the message box and return the DialogResult.

Checkbox Setup

The message box also comes with an optional checkbox. By default, the checkbox is hidden. Use the SetCheckbox() method to add a checkbox. It takes two arguments: the checkbox caption and the default checked value. The CheckboxChecked property returns whether the checkbox was checked.

//Box with a checkbox.
MsgBox db = new MsgBox("This is a test message", 
                "This is a test title", MessageBoxIcon.Information);
db.SetCheckbox("Don't show this message again.", false);
db.ShowDialog(this); //shows the message box.
bool isChecked = db.CheckboxChecked;
//returns whether the checkbox was checked by user.

Inner Workings (Optional)

This is a brief summary of what is going on behind the scenes. The MsgBox class inherits from the System.Windows.Forms.Form class. Initially, the form has three button controls, a checkbox control, and a label control. The buttons and checkbox are hidden and become visible when the SetButtons() and SetCheckbox() methods are called.

The most interesting part is auto sizing the form. The form must fit all the controls (and add proper spacing and margins). The controls will have unknown sizes because they will depend on the text assigned to them. For instance, the buttons will vary in width depending on the captions set in the SetButtons() method. The trick is to set the Control.AutoSize property to true on all the controls in order to auto-size the control. Once the controls are set up and the user calls ShowDialog() method, the Form.Load event is fired and my setDialogSize() method is called. This method adds up all the controls' height/width (from Control.Size.Height and Control.Size.Width properties), plus all the spacing and margins, and sets the Form's height and width.

The final step is the button/checkbox row placement. In the Form.Load event handler, there is a call to my setButtonRowLocations() method. This calculates the placement of the buttons in the bottom right corner based on their widths and the checkbox is always placed in the bottom left corner.

Refer to the source files for the full implementation of the setDialogSize() and setButtonRowLocations() methods.

Other mentions

The message box also has a SetMinSize() method which sets the minimum dimensions of the message box. If the text size is greater than the minimum size, then the message box will increase in size in order to fit the text. I would recommend using this method if the message is really small, but you don't want the message box to be small.

The ShowDialog() method used in all examples is a standard Form.ShowDialog() method. Use the proper version of this method to accommodate your code.

This class inherits the Form class so it is customizable. For instance, you can easily set the MsgBox.Icon property to add an icon in the title bar.

Here is a screenshot of a sample message box:

Custom_MessageBox/CustomMessageBox.png

License

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

Share

About the Author

Max Kleyzit
Software Developer http://www.stresstimulus.com
United States United States
No Biography provided

Comments and Discussions

 
QuestionMy vote of 5 Pin Pinmemberashaseeb6-Oct-14 11:11 
Generalgood 1 Pinmemberashaseeb6-Oct-14 11:08 
GeneralRe: good 1 PinmemberMax Kleyzit8-Oct-14 1:56 
QuestionMsfBox Form - Can't see the three buttons and check box PinmemberAntonio Barros27-Aug-14 22:58 
AnswerRe: MsfBox Form - Can't see the three buttons and check box PinmemberMax Kleyzit1-Oct-14 8:25 
GeneralRe: MsfBox Form - Can't see the three buttons and check box PinmemberAntonio Barros1-Oct-14 11:46 
GeneralMy vote of 5 PinprofessionalVolynsky Alex27-Aug-14 13:20 
QuestionButtons aren't visible unless height of Msgbx.cs increase in sample project PinmemberMember 252452719-Aug-14 13:29 
AnswerRe: Buttons aren't visible unless height of Msgbx.cs increase in sample project PinmemberMax Kleyzit2-Oct-14 4:29 
QuestionAddition of a show method Pinmemberdancingreality6-Aug-14 9:34 
Generalhelpful vote 5 PinmemberSamir Fatah6-Feb-12 0:42 
thanks good job
GeneralA Common Desire: similar work PinmemberJohn Whitmire1-Mar-11 10:28 
GeneralRe: A Common Desire: similar work PinmemberMax Kleyzit2-Mar-11 4:25 
GeneralRe: A Common Desire: similar work PinmemberJohn Whitmire3-Mar-11 3:42 
GeneralRe: A Common Desire: similar work PinmemberPSU Steve3-Mar-11 3:24 
Questionscrollable messagebox ?? Pinmemberalhambra-eidos1-Mar-11 3:03 
GeneralAdded few lines to center on screen [modified] Pinmemberfedesanp28-Feb-11 23:02 
GeneralRe: Added few lines to center on screen PinmemberMax Kleyzit1-Mar-11 4:00 
GeneralRe: Added few lines to center on screen Pinmemberfedesanp1-Mar-11 5:30 
GeneralMy vote of 5 PinmvpLuc Pattyn28-Feb-11 12:58 
GeneralRe: My vote of 5 PinmemberMax Kleyzit2-Mar-11 4:25 
GeneralMy vote of 5 PinmemberAhmad Hyari25-Feb-11 11:56 
GeneralRe: My vote of 5 PinmemberMax Kleyzit2-Mar-11 4:25 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 26 Aug 2014
Article Copyright 2011 by Max Kleyzit
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid