Example: Displaying a Dialog Box via a Menu Command
This topic contains procedures to:
-
Display a modal dialog box through a menu command.
-
Display a modeless dialog box through a menu command.
Both sample procedures are for MFC applications and will work in an application you create with the MFC Application Wizard.
The procedures use the following names and values:
| Item | Name or value |
|---|---|
| Application | DisplayDialog |
| Menu command | Test command on View menu; Command ID = ID_VIEW_TEST |
| Dialog box | Test dialog box; Class = CTestDialog; Header file = TestDialog.h; Variable = testdlg, ptestdlg |
| Command handler | OnViewTest |
To display a modal dialog box
-
Create the menu command; see Creating Menus or Menu Items.
-
Create the dialog box; see Starting the Dialog Editor.
-
Add a class for your dialog box. See Adding a Class for more information.
-
In Class View, select the document class (CDisplayDialogDoc). In the Properties window, click the Events button. Double-click the ID of the menu command (ID_VIEW_TEST) in the left pane of the Properties window and select Command. In the right pane, click the down arrow and select <Add> OnViewTest.
If you added the menu command to the mainframe of an MDI application, select the application class (CDisplayDialogApp) instead.
-
Add the following include statement to CDisplayDialogDoc.cpp (or CDisplayDialogApp.cpp) after the existing include statements:
#include "TestDialog.h"
-
Add the following code to OnViewTest to implement the function:
CTestDialog testdlg; testdlg.DoModal();
To display a modeless dialog box
-
Do the first four steps to display a modal dialog box, except select the view class (CDisplayDialogView) in step 4.
-
Edit DisplayDialogView.h:
-
Declare the dialog box class preceding the first class declaration:
class CTestDialog;
-
Declare a pointer to the dialog box after the Attributes public section:
CTestDialog* ptestdlg;
-
-
Edit DisplayDialogView.cpp:
-
Add the following include statement after the existing include statements:
#include "TestDialog.h"
-
Add the following code to the constructor:
ptestdlg = NULL;
-
Add the following code to the destructor:
delete ptestdlg;
-
Add the following code to OnViewTest to implement the function:
ptestdlg = new CTestDialog(this); ptestdlg ->Create(CTestDialog::IDD,this); ptestdlg ->ShowWindow(SW_SHOW);
-
Also, see the following Knowledge Base article:
-
Q251059 : HOWTO: Provide Your Own Window Class Name for an MFC Dialog Box