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.
- 'static DialogResult result = DialogResult.No; //DialogResult is returned by dialogs after dismissal.'
Creating Own MessageBox Control.
To create our own MessageBox control simply follow the guide below...
Open up your instance of Visual Studio (VS 2008/2010/2012/2015/2017)
Go to the toolbar at the top and click File -> New Project --> Windows Forms Application --> Give the project a name and then click ok.
Once loaded, drag and drop a button control from the Toolbox (found on the left) onto the form (as shown below).
Double click the button and the Integrated Development Environment will automatically generate the click event handler for you.
Edit the code for the form so that it looks like the following (You can right-click the form and click Edit Code):
Solution Explorer -> Right Click on your project --> Add --> Windows Form and set the name as "CustomMsgBox.cs"
Drag in a button & label control from the Toolbox to the form (It'll look something like the form below after doing it):
- Now write out the code below into the newly created form:
- Now run the program by just pressing F5 Key. Congratulations, you've made a reusable control.
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.
Visual Studio --> Your current project (Windows Form) --> Solution Explorer --> Project Name --> Right Click --> Add --> Existing Item --> Then locate your existing .cs file.
Now there's one last thing to do in order to use the control. Add a using statement to your code, so that your assembly knows about its dependencies.
To display the messagebox, simply use the following...
CustomMsgBox.Show("Your Message for Message Box...","MSG","OK");