Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / C#
Article

Modal and Modeless Dialog Box in C#

Rate me:
Please Sign up or sign in to vote.
2.51/5 (25 votes)
16 Jun 2008CPOL4 min read 146.1K   2.3K   23   8
This article describes the basic idea about modal and modeless in C#.
DialogExample

Introduction

I am originally an NDIS and Visual C++ programmer. I developed many applications in Visual C++ which handled dialog boxes. Then I got my first assignment in .NET which works on both Modal and Modeless dialog boxes. So I dug through MSDN and wrote the applicaton.

This article describes the basic idea about modal and modeless in C#.

Background

The first and most obvious question is, what is the difference between the Modal and Modeless dialog box?

The difference between a modal and modeless dialog box is that, modal dialogs once invoked will not allow the users to access the parent window, whereas modeless dialogs will allow the user to work with the parent window.

A user cannot enter input in any other dialog or invoke a menu option except without explicitly closing the modal dialog within the application. But the user can leave the modeless dialog open and do anything after the modeless dialog is invoked.

Using the Code

.NET is a superb and advanced, developer-friendly technology. Developers can concentrate on business models and all technology-specific things .NET does for you.

Writing Modal and Modeless dialog box applications is simple as compared with VC++/MFC. .NET provides rich classes set for Windows applications which make life easier.

The Form class is a base class for form-based applications (SDI/MDI/Dialog based). It provides you all the basic infrastructure for Windows (e.g. windows message loop, MDI Container etc).

So there is not any special class for dialogs, SDI, MDI like CDialog, CFrameWnd in MFC. You have to write only following line to run your application that’s all.

C#
Application.Run(new Form1());

//Form1 is derived which is derived from Form.

This line initializes your application and also starts a message loop.

Showing a dialogbox is more simple than just calling ShowDialog() for modal dialog and Show() for modeless dialog that’s all.

In my application, one main form and two dialog boxes. Main form creates a Modal dialog box and Modeless creates a dialog box when a user clicks on buttons.

There are two classes, Modal and Modeless for each dialog box. Both are derived from the Form class. Implementations of classes are the same.

C#
class Modal : Form
{
//Implementation here
}

class Modeless : Form
{
//Implementation here

}

Next is displaying the dialog box:

Modeless dialog box can be displayed using following code:

C#
Modeless objModeless = new Modeless();
objModeless.dlgevent += InfoEvent;

//Modeless dialog box is displayed by Show method.
objModeless.Show();

The Show() method is not blocking. It displays the dialog box and retuns.

The Modal dialog box can be displayed using the following code:

C#
//Set event handler which is called by dialog box.
objModal.dlgevent += InfoEvent;

//ShowDialog dispalys dialog box.
//Return value in Modal constructor
if (DialogResult.OK == objModal.ShowDialog())
{
   m_ModalTN.Nodes.Add("Ok Pressed");
}

ShowDialog() is a blocking method. It blocks until form is closed or the OK, Cancel button is not pressed.

Now let's discuss with Button handling in a dialog box.

Button is a standard class. It provides having many methods and properties. I will discuss a few important properties here.

  1. DialogResult: This is one of the important properties. This value is returned by the ShowDialog method when a user clicks on this button.

    It returns DialogResult. DialogResult is assigned to a button which will work as OK and Cancel buttons.

    C#
    this.button2.DialogResult = DialogResult.OK;
    this.button3.DialogResult = DialogResult.Cancel;
    

    button2 and button3 buttons will work as OK and Cancel buttons. DialogResult.OK and DialogResult.Cancel are assigned to button2 and button3 in my code.

  2. Text: This property can change your button name.

The Form class provides two important properties which are useful for dialog based application.

  1. AcceptButton: This property makes default button for your form

    Whenever the user presses the ENTER key on the form then this property is hit.

  2. CancelButton: This property makes the Cancel button for your form.

    Whenever a user presses the ESC key on the form then this method is hit.

Code snippet is below:

C#
public Modal()
{
    InitializeComponent();

    //These values are returned from ShowDialog method.
    this.button2.DialogResult = DialogResult.OK;
    this.button3.DialogResult = DialogResult.Cancel;

    //Following code makes  default button and cancel button.
    AcceptButton = DefaultButton;
    CancelButton = Cancel;
}

I record all the dialog box actions in a treeview. I create the treeview on the main form.

The infoevent event is called whenever any action occurs on any of either dialog boxes.

This method also makes a bridge between the main form and other dialog boxes.

I created two tree’s head nodes Modeless and Modal.

C#
public Form1()
{
    InitializeComponent();

    ///Add two top nodes in tree
    m_ModelessTN = treeView1.Nodes.Add("Modeless");
    m_ModalTN = treeView1.Nodes.Add("Modal");
}

This method changes the main form background color. BackColor is the form properties that changes a form’s background color. This method finds an object type at runtime and adds the value in the corresponding node.

Corresponding Node

C#
private void InfoEvent(object sender, EventArgs e)
{
    Modeless objSrc = sender as Modeless;

    //Set background color
    this.BackColor = Color.FromArgb(new Random().Next(255), 0, 0);
    if (null != objSrc)
    {
        m_ModelessTN.Nodes.Add(objSrc.TEXT);
    }
    else
    {
        Modal objModalSrc = sender as Modal;
        if (null != objModalSrc)
        {
            m_ModalTN.Nodes.Add(objModalSrc.TEXT);
        }
    }

    treeView1.ExpandAll();
}

And last but not least, how to close your application. It is very simple. Just call the Close form method. I also added a Modeless Close button.

The following code is the handler of this button.

C#
private void ModelessClose(object sender, EventArgs e)
{
    objModeless.Close();
}

Points of Interest

This is my first post to Code Project. I am very happy. Code Project helps me lot, improving my capabilities.

License

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


Written By
Software Developer (Senior) Juniper Networks
India India
I started my programming with DOS. Now I am flying on C# sky.

Comments and Discussions

 
PraiseGREAT! Pin
Member 1184586222-May-16 13:51
Member 1184586222-May-16 13:51 
GeneralMy vote of 5 Pin
nmpina2822-Jun-12 6:57
nmpina2822-Jun-12 6:57 
GeneralMy vote of 4 Pin
Yawness8-May-12 21:59
Yawness8-May-12 21:59 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey3-Feb-12 0:03
professionalManoj Kumar Choubey3-Feb-12 0:03 
GeneralYou forgot to call Dispose() after ShowDialog() Pin
EFEaglehouse11-Mar-11 6:54
EFEaglehouse11-Mar-11 6:54 
One critical piece was omitted from the instructions about how to call ShowDialog(). After retrieving the results, you must also call Dispose() on the dialog form. This call is actually what destroys the form and allows the garbage collector to do its job.

ShowDialog() does not automatically call Dispose() when the form is closed, to allow you to retrieve the dialog result and any data the caller needs from the form. If Dispose() were called automatically, the form resources would be quickly (but not instantly) returned to the managed heap; if you try to access any resources, e.g. properties, after a Dispose(), you will most likely generate a ObjectDisposedException error. You can't access something that has already been destroyed.

Because of this, you must retrieve any resources from the form that you consider important, then call Dispose() manually after invoking a form with ShowDialog().
--
Ed Eaglehouse

Languages broken with standards confused,
No wonder I've got me the Programmer's Blues.

GeneralMy vote of 5 Pin
toshimi maruyama4-Aug-10 20:11
toshimi maruyama4-Aug-10 20:11 
GeneralMy vote of 1 Pin
Syed J Hashmi24-Jan-10 0:37
Syed J Hashmi24-Jan-10 0:37 

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.