Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / C#

Custom Message Box in VC#

Rate me:
Please Sign up or sign in to vote.
4.83/5 (11 votes)
8 Feb 2012CPOL2 min read 102.9K   4.6K   24   16
How to create custom message box in C#.NET

Introduction

In this article, I am going to explain how to create a custom message box in C#.NET. As we know, we can use a MessageBox class to display a message box, but that does not look beautiful. When we make a project, sometimes we need to create a custom message box because ordinary message box does not fill our requirements such as MessageBox which has check box control like Do Not Show Next time or has a gradient background color, etc. In this demo, I will tell you how to create a custom message box which has a gradient background color. For completing this demo, I used Visual Studio 2010 as IDE and C# as programming language.

In this demo, I created two classes, frmShowMessage which displays message box and frmMain class which is used to test application. Then I created two enumerations, one is enumMessageIcon which contains Icon for Image and the other one is enumMessageButton which contains type of buttons to be displayed.

frmShowMessage class has a static overloaded method named Show() which is used to display message. First type accepts one string parameter which is message needs to be displayed, second type accepts two string parameters, first is message to be displayed and second one is message title and the last one is accept four parameters, first one is messageText, second one is messageTitle, third one is messageIcon and last one is messageButton. You can create more overloaded methods according to your need. Let’s start with this demo.

First, create a form named frmShowMessage and write down the following lines of code. I had used ImageList control which contains all images to be displayed on frmShowMessage and creates two enumerations in the same namespace.

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace MessageBoxDemo
{
    public partial class frmShowMessage : Form
    {
        public frmShowMessage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Here I am overriding Paint method of form object
        /// and set it's background color as gradient. Here I am
        /// using LinearGradientBrush class object to make gradient
        /// color which comes in System.Drawing.Drawing2D namespace.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle rect = this.ClientRectangle;
            LinearGradientBrush brush = new LinearGradientBrush
            (rect, Color.SkyBlue, Color.AliceBlue, 60);
            e.Graphics.FillRectangle(brush, rect);
            base.OnPaint(e);
        }

        /// <summary>
        /// setMessage method is used to display message
        /// on form and it's height adjust automatically.
        /// I am displaying message in a Label control.
        /// </summary>
        /// <param name="messageText">Message which needs to be displayed to user.</param>
        private void setMessage(string messageText)
        {
            int number = Math.Abs(messageText.Length / 30);
            if (number != 0)
                this.lblMessageText.Height = number * 25;
            this.lblMessageText.Text = messageText;
        }

        /// <summary>
        /// This method is used to add button on message box.
        /// </summary>
        /// <param name="MessageButton">MessageButton is type of enumMessageButton
        /// through which I get type of button which needs to be displayed.</param>
        private void addButton(enumMessageButton MessageButton)
        {
            switch (MessageButton)
            {
                case enumMessageButton.OK:
                    {
                        //If type of enumButton is OK then we add OK button only.
                        Button btnOk = new Button();  //Create object of Button.
                        btnOk.Text = "OK";  //Here we set text of Button.
                        btnOk.DialogResult = DialogResult.OK;      //Set DialogResult 
                            //property of button.
                        btnOk.FlatStyle = FlatStyle.Popup;      //Set flat appearance 
                            //of button.
                        btnOk.FlatAppearance.BorderSize = 0;
                        btnOk.SetBounds(pnlShowMessage.ClientSize.Width - 80, 
                    5, 75, 25);  // Set bounds of button.
                        pnlShowMessage.Controls.Add(btnOk);  //Finally Add button control
                              // on panel.
                    }
                    break;
                case enumMessageButton.OKCancel:
                    {
                        Button btnOk = new Button();
                        btnOk.Text = "OK";
                        btnOk.DialogResult = DialogResult.OK;
                        btnOk.FlatStyle = FlatStyle.Popup;
                        btnOk.FlatAppearance.BorderSize = 0;
                        btnOk.SetBounds((pnlShowMessage.ClientSize.Width - 70), 
                    5, 65, 25);
                        pnlShowMessage.Controls.Add(btnOk);

                        Button btnCancel = new Button();
                        btnCancel.Text = "Cancel";
                        btnCancel.DialogResult = DialogResult.Cancel;
                        btnCancel.FlatStyle = FlatStyle.Popup;
                        btnCancel.FlatAppearance.BorderSize = 0;
                        btnCancel.SetBounds((pnlShowMessage.ClientSize.Width - 
                (btnOk.ClientSize.Width + 5 + 80)), 5, 75, 25);
                        pnlShowMessage.Controls.Add(btnCancel);

                    }
                    break;
                case enumMessageButton.YesNo:
                    {
                        Button btnNo = new Button();
                        btnNo.Text = "No";
                        btnNo.DialogResult = DialogResult.No;
                        btnNo.FlatStyle = FlatStyle.Popup;
                        btnNo.FlatAppearance.BorderSize = 0;
                        btnNo.SetBounds((pnlShowMessage.ClientSize.Width - 70), 
                    5, 65, 25);
                        pnlShowMessage.Controls.Add(btnNo);

                        Button btnYes = new Button();
                        btnYes.Text = "Yes";
                        btnYes.DialogResult = DialogResult.Yes;
                        btnYes.FlatStyle = FlatStyle.Popup;
                        btnYes.FlatAppearance.BorderSize = 0;
                        btnYes.SetBounds((pnlShowMessage.ClientSize.Width - 
                (btnNo.ClientSize.Width + 5 + 80)), 5, 75, 25);
                        pnlShowMessage.Controls.Add(btnYes);
                    }
                    break;
                case enumMessageButton.YesNoCancel:
                    {
                        Button btnCancel = new Button();
                        btnCancel.Text = "Cancel";
                        btnCancel.DialogResult = DialogResult.Cancel;
                        btnCancel.FlatStyle = FlatStyle.Popup;
                        btnCancel.FlatAppearance.BorderSize = 0;
                        btnCancel.SetBounds
            ((pnlShowMessage.ClientSize.Width - 70), 5, 65, 25);
                        pnlShowMessage.Controls.Add(btnCancel);

                        Button btnNo = new Button();
                        btnNo.Text = "No";
                        btnNo.DialogResult = DialogResult.No;
                        btnNo.FlatStyle = FlatStyle.Popup;
                        btnNo.FlatAppearance.BorderSize = 0;
                        btnNo.SetBounds((pnlShowMessage.ClientSize.Width - 
            (btnCancel.ClientSize.Width + 5 + 80)), 5, 75, 25);
                        pnlShowMessage.Controls.Add(btnNo);

                        Button btnYes = new Button();
                        btnYes.Text = "Yes";
                        btnYes.DialogResult = DialogResult.No;
                        btnYes.FlatStyle = FlatStyle.Popup;
                        btnYes.FlatAppearance.BorderSize = 0;
                        btnYes.SetBounds((pnlShowMessage.ClientSize.Width - 
            (btnCancel.ClientSize.Width + btnNo.ClientSize.Width + 
                10 + 80)), 5, 75, 25);
                        pnlShowMessage.Controls.Add(btnYes);
                    }
                    break;
            }
        }

        /// <summary>
        /// We can use this method to add image on message box.
        /// I had taken all images in ImageList control so that
        /// I can easily add images. Image is displayed in 
        /// PictureBox control.
        /// </summary>
        /// <param name="MessageIcon">Type of image to be displayed.</param>
        private void addIconImage(enumMessageIcon MessageIcon)
        {
            switch (MessageIcon)
            {
                case enumMessageIcon.Error:
                    pictureBox1.Image = imageList1.Images["Error"];  //Error is key 
            //name in imagelist control which uniquely identified images 
            //in ImageList control.
                    break;
                case enumMessageIcon.Information:
                    pictureBox1.Image = imageList1.Images["Information"];
                    break;
                case enumMessageIcon.Question:
                    pictureBox1.Image = imageList1.Images["Question"];
                    break;
                case enumMessageIcon.Warning:
                    pictureBox1.Image = imageList1.Images["Warning"];
                    break;
            }
        }

        #region Overloaded Show message to display message box.

        /// <summary>
        /// Show method is overloaded which is used to display message
        /// and this is static method so that we don't need to create 
        /// object of this class to call this method.
        /// </summary>
        /// <param name="messageText"></param>
        internal static void Show(string messageText)
        {
            frmShowMessage frmMessage = new frmShowMessage();
            frmMessage.setMessage(messageText);
            frmMessage.addIconImage(enumMessageIcon.Information);
            frmMessage.addButton(enumMessageButton.OK);
            frmMessage.ShowDialog();
        }

        internal static void Show(string messageText, string messageTitle)
        {
            frmShowMessage frmMessage = new frmShowMessage();
            frmMessage.Text = messageTitle;
            frmMessage.setMessage(messageText);
            frmMessage.addIconImage(enumMessageIcon.Information);
            frmMessage.addButton(enumMessageButton.OK);
            frmMessage.ShowDialog();
        }

        internal static void Show(string messageText, string messageTitle, 
        enumMessageIcon messageIcon, enumMessageButton messageButton)
        {
            frmShowMessage frmMessage = new frmShowMessage();
            frmMessage.setMessage(messageText);
            frmMessage.Text = messageTitle;
            frmMessage.addIconImage(messageIcon);
            frmMessage.addButton(messageButton);
            frmMessage.ShowDialog();
        }

        #endregion
    }

    #region constant defined in form of enumeration which is used in showMessage class.

    internal enum enumMessageIcon
    {
        Error,
        Warning,
        Information,
        Question,
    }

    internal enum enumMessageButton
    {
        OK,
        YesNo,
        YesNoCancel,
        OKCancel
    }

    #endregion
}

Now create a frmMain form which is your main form or we can say start up form and write down the following code to test it:

C#
using System;
using System.Windows.Forms;

namespace MessageBoxDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        /// <summary>
        /// On Click event of button I am showing user defined message box.
        /// Here I am showing message box with three type of parameters.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            frmShowMessage.Show("This is message box which represent message with title, 
        custom button and custom icon.", "This is message title", 
        enumMessageIcon.Question, enumMessageButton.OKCancel);
        }
    }
}

After creating these two classes and writing code, build your program and see the output which is as follows:

image002.jpg

image004.jpg

Please write your valuable comments. Thanks.

History

  • 7th January, 2012: Initial version

License

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


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

Comments and Discussions

 
QuestionHow to get the dialog result from the buttons? Pin
Member 1481057717-Jul-21 6:01
Member 1481057717-Jul-21 6:01 
Questionhow to use buttons Pin
Member 1220845326-Mar-19 0:14
Member 1220845326-Mar-19 0:14 
QuestionToo many No's Pin
ronsimon11-Apr-14 7:14
ronsimon11-Apr-14 7:14 
QuestionCustom MessageBox Pin
Member 990228924-Jan-14 9:25
Member 990228924-Jan-14 9:25 
QuestionMessageBox Pin
Member 1025570827-Nov-13 7:15
Member 1025570827-Nov-13 7:15 
QuestionDialogResult Pin
dabeeyow24-Nov-13 17:28
dabeeyow24-Nov-13 17:28 
How to get DialogResult of this custom messagebox? Thanks in advance.
AnswerRe: DialogResult Pin
ronsimon19-Apr-14 11:08
ronsimon19-Apr-14 11:08 
QuestionMinor Correction (sorry for VB.NET code) Pin
sparky27785-Dec-12 11:57
sparky27785-Dec-12 11:57 
QuestionWhy? Pin
KeithAMS15-Feb-12 2:31
KeithAMS15-Feb-12 2:31 
AnswerRe: Why? Pin
Awadhendra123415-Feb-12 7:21
Awadhendra123415-Feb-12 7:21 
AnswerRe: Why? Pin
Yves8-Apr-12 12:49
Yves8-Apr-12 12:49 
SuggestionSource code in zip file please. Pin
Septimus Hedgehog8-Feb-12 8:59
Septimus Hedgehog8-Feb-12 8:59 
GeneralRe: Source code in zip file please. Pin
Awadhendra12348-Feb-12 9:06
Awadhendra12348-Feb-12 9:06 
GeneralRe: Source code in zip file please. Pin
Septimus Hedgehog8-Feb-12 9:42
Septimus Hedgehog8-Feb-12 9:42 
SuggestionRe: Source code in zip file please. Pin
Septimus Hedgehog8-Feb-12 22:00
Septimus Hedgehog8-Feb-12 22:00 
GeneralRe: Source code in zip file please. Pin
Awadhendra12349-Feb-12 6:48
Awadhendra12349-Feb-12 6:48 

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.