Programming a Modal Dialog Box
Modal dialog boxes are the most frequently used dialog boxes. A user action (a menu choice, for example) brings up a dialog box on the screen, the user enters data in the dialog box, and then the user closes the dialog box. Here's a summary of the steps to add a modal dialog box to an existing project:
Use the dialog editor to create a dialog resource that contains various controls. The dialog editor updates the project's resource script (RC) file to include your new dialog resource, and it updates the project's
Use the MFC Class Wizard to create a dialog class derived from CDialog and attached to the resource created in step 1. Visual Studio adds the associated code and header file to the Microsoft Visual C++ project.
| Note | When Visual Studio generates your derived dialog class, it generates a constructor that invokes a CDialog modal constructor, which takes a resource ID as a parameter. Your generated dialog header file contains the class enumerator constant IDD, which is set to the dialog resource ID. In the CPP file, the constructor implementation looks like this: IMPLEMENT_DYNAMIC(CMyDialog, CDialog) The use of enum IDD decouples the CPP file from the resource IDs that are defined in the project's |
Use Visual Studio to add data members, exchange functions, and validation functions to the dialog class.
Use Class View's Properties window to add message handlers for the dialog box's buttons and other event-generating controls.
Write the code for special control initialization (in OnInitDialog) and for the message handlers. Be sure the CDialog virtual member function OnOK is called when the user closes the dialog box (unless the user cancels the dialog box). (Note: OnOK is called by default.)
Write the code in your view class to activate the dialog box. This code consists of a call to your dialog class's constructor followed by a call to the DoModal dialog class member function. DoModal returns only when the user exits the dialog box.
Now we'll proceed with a real example, one step at a time.