MessageBox.Show() is a great way get user confirmation before performing certain tasks in .NET. However what if your requirements are more complex then simply getting a YES or NO response? What if you want to get the user to enter in a password? Or you just want to change the design of the existing MessageBox to go with the design of your application. Creating a custom MessageBox dialog will solve this problem and bring greater functionality to your application.
The example below is very simple, however you can make your custom message box as complex as you would like
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CustomMessageBox
{
public partial class CustomMessageBox : Form
{
public static int rVal = 0;
static CustomMessageBox newCustomMessageBox;
public CustomMessageBox()
{
InitializeComponent();
}
public static int ShowBox()
{
newCustomMessageBox = new CustomMessageBox();
newCustomMessageBox.ShowDialog();
return rVal;
}
private void btnOK_Click(object sender, EventArgs e)
{
//Add code here to process the password
if (tbPswd.Text == "hello")
{
rVal = 1;
}
else
{
rVal = 2;
}
newCustomMessageBox.Dispose();
}
private void btnCancel_Click(object sender, EventArgs e)
{
rVal = 0;
newCustomMessageBox.Dispose();
}
}
}
Using your custom dialog is just as simple as using MessageBox:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CustomMessageBox
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int rVal = CustomMessageBox.ShowBox();
label1.Text = "Return: " + rVal;
}
}
}
Download Source Code