How to set up a modal dialog form

ddanbe 3 Tallied Votes 889 Views Share

A modal dialog is a window that you must respond to.
The MessageBox for example is such a window. It is a handy tool for displaying a warning or other kind of message to the user. But, you can configure it only in a limited way.
Xcelled194 did a good job on setting up a VB style inputbox,
http://www.daniweb.com/software-development/csharp/code/361925

So I propose here a way to simulate a MessageBox an InputForm an AboutBox or whatever, where you are in total control on how it looks and behaves. Many users over here like to change the behaviour of a MessageBox, well, this is a way to go!

First start a new WindowsFormApplication or add a Windows Form to your project with Add Item… Give this file an appropriate name. I called it DialogBox.cs.
Next we add two buttons that are almost omnipresent in this kind of window: the OK and the Cancel button. If you don’t want them or like to call them Yes or No or whatever you can always do whatever you please. If you don’t want to, you don’t have to implement Click event handlers here.
I give them the following properties:
OK button

Name = OKBtn Text = OK DialogResult = OK

Cancel button

Name = CancelBtn Text = Cancel DialogResult = Cancel

For the form set the following properties:

AcceptButton = OKBtn
(The button named “OKBtn” will also react on enter&return keypress)
CancelButton = CancelBtn
(The button named “CancelBtn” will also react on ESC keypress)
BorderStyle = FixedDialog
MinimizeBox = false
MaximizeBox = false
ShowInTaskBar = false
StartPosition = CenterParent

You could even make a project item template out of it if you are going to use this often: http://msdn.microsoft.com/en-us/library/tsyyf0yh.aspx

Now this is just the basic set up. It is up to you to add pictureboxes, labels, textboxes etc.
You could even add some properties. Like the FileName property of the OpenFileDialog for example.
Happy computing!

//Typical use

            DialogBox MyDialog = new DialogBox();
            MyDialog.ShowDialog(); //Show as modaldialog
            if (MyDialog.DialogResult == DialogResult.OK)
            {
                // pseudocode
                // thisform.aField = MyDialog.aProperty;
                // etc.
            }
ddanbe 2,724 Professional Procrastinator Featured Poster

Correction:
BorderStyle should be FormBorderStyle

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.