Forms and dialog boxes are either modal or modeless. A modal form or dialog box must be closed (hidden or unloaded) before you can continue working with the rest of the application. For example, a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box. For more information about working with dialog boxes, see How to Handle User Input to Dialog Boxes.
Dialog boxes that display important messages should always be modal — that is, the user should always be required to close the dialog box or respond to its message before proceeding. Often, MessageBox is used to show information in this fashion, as it requires the user to close it before proceeding.
Modeless forms and dialog boxes let you shift the focus between the form or dialog box and another form without having to close the initial form or dialog box. The user can continue to work elsewhere in any application while the form or dialog box is displayed.
Modeless forms and dialog boxes are harder to program, because users can access them in an unpredictable order. You have to keep the state of the application consistent no matter what the user does. Often, tool windows are shown in a modeless fashion. A Find and Replace dialog box, is an example of a modeless dialog box. Use modeless forms and dialog boxes to display frequently used commands or information.
To display a form as a modal dialog box
The following example shows how to display an About dialog box modally.
[Visual Basic]
Dim f As frmAbout = New frmAbout
' Display frmAbout as a modal dialog.
f.ShowDialog
[C#]
' Display frmAbout as a modal dialog
Form frmAbout = new Form();
FrmAbout.ShowDialog();
The ShowDialog method has an optional argument, owner, that can be used to specify a parent-child relationship for a form. For example, when code in your main form shows a dialog box, you can pass Me (in Visual Basic) or this (in C#) as the owner of the dialog box to establish your main form as the owner, as the following code shows.
[Visual Basic]
Private Sub mnuAbout_Click(…args…)
Dim f As frmAbout = New frmAbout
f.ShowDialog Me
End Sub
[C#]
Note If a form is displayed as modal, the code following the ShowDialog method is not executed until the dialog box is closed. However, when a form is shown as modeless, the code following the Show method is executed immediately after the form is displayed.
To display a form as a modeless dialog box
The following example shows how to display an About dialog box in modeless format.
[Visual Basic]
Dim f As frmAbout = New frmAbout
' Display frmAbout as a modeless dialog.
f.Show
[C#]
' Display frmAbout as a modaless dialog
Form frmAbout = new Form();
FrmAbout.Show();
Introduction to Win Forms | Win Forms Creation | Retrieving Dialog Box Information Using Multiple Properties | Retrieving Dialog Box Information Using Objects | Creating Transparent Win Forms | Resizing Win Forms | Setting the Location of Win Forms | Dialog Boxes | Treating Forms as Objects