Programming a Modal Dialog
Modal dialogs are the most frequently used dialogs. A user action (a menu choice, for example) brings up a dialog on the screen, the user enters data in the dialog, and then the user closes the dialog. Here's a summary of the steps to add a modal dialog 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 resource.h file with corresponding #define constants.
- Use ClassWizard to create a dialog class that is derived from CDialog and attached to the resource created in step 1. ClassWizard adds
the associated code and header file to the Microsoft Visual C++ project.
When ClassWizard 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 a class enumerator constant IDD that is set to the dialog resource ID. In the
CPP file, the constructor implementation looks like this:
CMyDialog::CMyDialog(CWnd* pParent /*=NULL*/)
: CDialog(CMyDialog::IDD, pParent)
// initialization code here
The use of enum IDD decouples the CPP file from the resource IDs that are defined in the project's resource.h file.
- Use ClassWizard to add data members, exchange functions, and validation functions to the dialog class.
- Use ClassWizard to add message handlers for the dialog'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 (unless the user cancels the dialog). (Note: OnOK is called by default.)
- Write the code in your view class to activate the dialog. 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 window.
Now we'll proceed with a real example, one step at a time.