# Creating Own MessageBox in Windows Form Application
First we need to know what a MessageBox is...
The MessageBox control displays a message with specified text, and can be customised by specifying a custom image, title and button sets (These button sets allow the user to choose more than a basic yes/no answer).
By creating our own MessageBox we can re-use that MessageBox Control in any new applications just by using the generated dll, or copying the file containing the class.
# Creating Own MessageBox Control.
To create our own MessageBox control simply follow the guide below...
namespace MsgBoxExample {
public partial class MsgBoxExampleForm : Form {
//Constructor, called when the class is initialised.
public MsgBoxExampleForm() {
InitializeComponent();
}
//Called whenever the button is clicked.
private void btnShowMessageBox_Click(object sender, EventArgs e) {
CustomMsgBox.Show($"I'm a {nameof(CustomMsgBox)}!", "MSG", "OK");
}
}
}
- Now write out the code below into the newly created form:
private DialogResult result = DialogResult.No;
public static DialogResult Show(string text, string caption, string btnOkText) {
var msgBox = new CustomMsgBox();
msgBox.lblText.Text = text; //The text for the label...
msgBox.Text = caption; //Title of form
msgBox.btnOk.Text = btnOkText; //Text on the button
//This method is blocking, and will only return once the user
//clicks ok or closes the form.
msgBox.ShowDialog();
return result;
}
private void btnOk_Click(object sender, EventArgs e) {
result = DialogResult.Yes;
MsgBox.Close();
}
# How to use own created MessageBox control in another Windows Form application.
To find your existing .cs files, right click on the project in your instance of Visual Studio, and click Open Folder in File Explorer.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
.
.
.
using CustomMsgBox; //Here's the using statement for our dependency.
# Syntax
- 'static DialogResult result = DialogResult.No; //DialogResult is returned by dialogs after dismissal.'