Using Dialog Boxes

You’ve met dialog boxes before—the About dialog box possessed by just about every application, for example, or the Insert Table dialog box in Microsoft Word.

In the .NET Framework, the difference between dialog boxes and other kinds of windows is rather blurred, and a dialog box is just another form. However, that hasn’t always been the case in Microsoft Windows programming. Before .NET, dialog boxes had several special properties:

  • They were windows that were optimized to work with controls.

  • They usually had a fixed border so that you couldn’t resize them.

  • They could be described in data using a dialog box template, and they could be automatically created and populated with controls at run time. This data was attached to the executable as a binary Windows resource.

  • They could be created as modal dialog boxes, in which case the application was blocked until the dialog box was sent away, or as modeless dialog boxes, in which case the dialog box window floated on top of its parent window and you could use both.

Windows Forms has some of these properties already. You can easily use controls on forms, and you can set the border so that the form can’t be resized. However, you can’t use dialog box templates because .NET doesn’t use resources. You have to build dialog boxes in code, just like any other form. To help you design forms that work like modal dialog boxes, the Form class has a ShowDialog function that displays a form modally, so you have to close the form before you can use the rest of the application.

The following exercise continues the CppForm project that you began in Chapter 16 and shows you how to create an About dialog box for your application.


If you haven’t worked through the examples in Chapter 16, you’ll find the code for the CppForm project with the sample files. You can use this code as the basis for the first exercises in this chapter.

start sidebar
Dialog Box Design

As with menus, you should be aware of a couple of design guidelines when designing dialog boxes. If the dialog box simply exists to display some data— such as a reminder—to the user, it should include a button that the user can use to dismiss the dialog box. This button should be labeled with OK, Done, or another word indicating that the user is finished with the dialog box.

If the user enters data into the dialog box, it should include two buttons. One button will accept the changes and dismiss the dialog box and is conventionally labeled OK, while the other button will discard the changes before dismissing the dialog box and is normally labeled Cancel. These buttons are usually placed in a horizontal row at the bottom of the dialog box.

On a more general note, don’t make dialog boxes too cluttered. It’s better to have several dialog boxes that do one thing well than one giant dialog box that is a mess of controls. You might also want to consider investigating tabbed dialog boxes, which can help to reduce clutter.

end sidebar

  1. Open the CppForm project if it isn’t already open.

  2. Right-click the project name CppForm in Solution Explorer, and choose Add and then Add New Item from the context menu. Make sure that the Windows Form (.NET) icon is highlighted in the Templates pane, and enter the name AboutBox for the new form.

    click to expand

    A dialog box is simply another form, and the main difference from the application’s main form lies in how you display it, as you’ll see shortly.

  3. When the designer window for the dialog box appears, set the properties for the dialog box so that the caption is About CppForm, the border style is Fixed3D, and the size is 300,150. The style is set to Fixed3D because dialog boxes usually are not resizable.

  4. The dialog box is going to show two labels and an OK button. Drag a Label onto the form, positioning it at 20,30 and giving it the text The CppForm Application. Alter the size of the label so that all the text appears on one line.

  5. Drag a second label onto the form, positioning it below the first and giving it the text Julian Templeman, 2001.

  6. Add a button to the form, giving it the name OKButton and the text OK, and setting its size to 40,25. Position it toward the lower right corner of the form.

  7. Add an event handler for the button. Bring up the properties for the button, and make the editor display events by pressing the Event button at the top of the editor. Locate the Click event, and double-click in the blank space to the right of the word Click. Complete the handler function as shown below:

    private: System::Void OKButton_Click(System::Object * sender, EventArgs * e) { // Close the form Close(); }

    The handler function simply closes the form when the button is clicked.

  8. The last step is to arrange for the dialog box to be displayed when the About menu item is selected. Because we need to access the AboutBox class from the main form, open the code for Form1.h, and insert #include “AboutBox.h” at the top of the file. Locate the CppForm::MenuItem_Clicked function, and edit the code as follows, adding the lines shown in bold in the following listing:

    private: System::Void aboutMenuItem_Click(System::Object * sender, System::EventArgs * e) { AboutBox* box = new AboutBox();  box->ShowDialog(); }

    When the About menu item is chosen, create an AboutBox object and then call its ShowDialog function, which has the effect of displaying the form as a modal dialog box so that it has to be closed before you can continue working with the application.

  9. Build and run the application. When you select the About item on the File menu, you should see the About dialog box displayed.

The DialogResult Property

It’s common for dialog boxes to contain a set of buttons—such as Yes, No, and Cancel, or Abort, Retry, and Ignore—that the user can use to pass information back to the application. The DialogResult property is used to pass a value back to the calling code that shows which button was clicked to dismiss the dialog box. The property will take one of the values from the DialogResult enumeration, whose values are shown in the following table.




Represents the return value Abort and is usually set by a button labeled Abort


Represents the return value Cancel and is usually set by a button labeled Cancel


Represents the return value Ignore and is usually set by a button labeled Ignore


Represents the return value No and is usually set by a button labeled No


Nothing is returned from the dialog box, so the modal dialog box continues running


Represents the return value OK and is usually set by a button labeled OK


Represents the return value Retry and is usually set by a button labeled Retry


Represents the return value Yes and is usually set by a button labeled Yes

You might be slightly puzzled by the description of the None entry, and I need to explain how DialogResult works.

A user will typically dismiss a dialog box by clicking a button, and you’ve already seen how the handler for the OK button was used to close the About box in the previous exercise. If you want to pass back a return value from a modal dialog box, assign one of the values from the table to the form’s DialogResult property. However, doing so has the effect of assigning the value and immediately closing the form. So you could replace the OK button handler in the previous exercise with the following code:

private: System::Void OKButton_Click(System::Object * sender, System::EventArgs * e) { // Send back ’OK’ and close the form DialogResult = DialogResult::OK; } 

The caller can check the value returned from ShowDialog to find out what the dialog box returned.

In fact, it can be even easier to close the form and send a value back to the caller. Button controls have a DialogResult property. If this property is set to a value other than None, clicking the button closes the parent form and sends the appropriate result back. Once you have set the DialogResult for the button, you can remove the Click handler for the button. Select the button, open the Properties editor, display the events, and delete the OKButton_Click entry. Note that this doesn’t delete the handler function itself, but simply unlinks it from the button. You can tidy up the code by manually deleting the OKButton_Click function from Form1.h.

Using Data with Dialog Boxes

It’s common to use dialog boxes to obtain information from the user. You often have to load data into the dialog box before displaying it and then extract the data that the user entered, usually when the user clicks OK. The following exercise is an example of a dialog box that displays information, lets the user change it, and then reads the changes when it is dismissed.

  1. Open the CppForm project if it isn’t already open. Right-click the project name in Solution Explorer, and choose Add and then Add New Item from the context menu. Make sure that the Windows Form (.NET) entry is selected in the Templates pane, and add a new form named MyDialog.

  2. Open the code window for the main form, Form1.h, and add an #include “MyDialog.h” line so that the new form can be referenced from the main form.

  3. The dialog box is going to contain controls to gather a user’s personal details, which in this case will be name, phone number, and department. Each of these items will need a control and a label, and you’ll also need OK and Cancel buttons to dismiss the dialog box. Add the eight controls to the MyDialog form, arranging them to look like the following figure.

    The name and phone fields are represented by TextBox controls named nameBox and phoneBox, and the department is represented by a ComboBox control named deptCombo. Remove the default text from the Text property of the TextBox and ComboBox controls so that they are blank.

  4. Use the Properties editor to set up the form and the controls. Set the form to be 280,200 pixels in size with a Fixed3D border style and the caption Personal Details. Set the TextAlign for the labels to MiddleRight.

  5. The combo box will hold a list of departments, and you can add these strings using the Properties editor. Select the ComboBox, find the Items property in the Properties editor, and click the ellipses (...) button to the right of the property. The String Collection Editor, which you can use to specify the strings that will be displayed in the combo box will open. Add the strings IT, Admin, R&D, Catering, and Manufacturing, one per line, and close the editor when you’re done.

  6. Give the OK and Cancel buttons the names OKButton and CancelButton, respectively, and set their DialogResult properties to DialogResult::OK and DialogResult::Cancel.

    Because each button has its DialogResult member set, when they’re clicked, they’ll both dismiss the dialog box and return a DialogResult to the calling code.

  7. Now set the AcceptButton and CancelButton properties of the form. If set, the AcceptButton holds a reference to the button that is the default button on the form. Set the AcceptButton property to OKButton. Pressing the Enter key has the same effect as clicking the default button, and since we’ve set the DialogResult for OKButton to OK, pressing Enter will dismiss the dialog box and send DialogResult::OK back to the caller. The form’s CancelButton property holds a reference to the button that maps onto the Esc key, thus giving the user a way to dismiss the dialog box from the keyboard. Note that the CancelButton property does not seem to work correctly in the late beta version of Visual Studio .NET 7.1 that was used when writing this book.

  8. To let the calling code get and set the values in the controls, add properties to the class, like this:

    // Properties for accessing control data public: __property void set_Name(String* n) { nameBox->Text = n; } __property String* get_Name() { return nameBox->Text; } __property void set_Phone(String* p) { phoneBox->Text = p; } __property String* get_Phone() { return phoneBox->Text; } __property void set_Dept(int d) { deptCombo->SelectedIndex = d; } __property int get_Dept() { return deptCombo->SelectedIndex; }

    There’s a pair of get and set methods for each field in the dialog box, and these will let the user of the MyDialog class manipulate the data without giving them complete access to the TextBox and ComboBox objects.

  9. Add the code to display the dialog box. Display the main form, add a new menu item to the File menu, and give it the text Display Dialog.... Remember that the ellipses (...)on a menu item name means that the item is going to display a dialog box. In the menu editor, drag the new item so that it is between the About and Exit items. Give the menu item the name dialogMenuItem.

  10. Double-click the new menu item to create a handler for it, and edit the code for the handler so that it displays the dialog box.

    private: System::Void dialogMenuItem_Click(System::Object * sender, System::EventArgs * e) { // Create the dialog MyDialog* box = new MyDialog(); // Fill in the initial data box->Name = S"Joe Bloggs"; box->Phone = S"555-0155"; box->Dept = 1; // Show the dialog if (box->ShowDialog() == DialogResult::OK) { // If it came back with OK, display the name MessageBox::Show(box->Name, S"Name was..."); } } 

    After the dialog box object has been created, you use the properties to put the initial data into the controls. The dialog box is then shown to the user using ShowDialog, and when it returns, you can check the return value and see whether it was DialogResult::OK or DialogResult::Cancel. If it was OK, you can then use the Name property to extract the final data from the dialog box object.

  11. Build and run the code, and when you select the MyDialog menu item, you should see the dialog box display with its initial data.

Setting Tab Ordering

You can use the Tab key to move from control to control on a form. By default, the order in which you move between controls follows the order in which they’re created, but you can impose your own order by assigning a zero-based value to the TabIndex property of any control.

It isn’t an error for two controls to have the same TabIndex value, but the order in which they are selected will depend on the order in which they are displayed on the screen.

Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
Year: 2003
Pages: 208 © 2008-2017.
If you may any questions please contact us: