Export (0) Print
Expand All

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

  1. Create the menu command; see Creating Menus or Menu Items.

  2. Create the dialog box; see Starting the Dialog Editor.

  3. Add a class for your dialog box. See Adding a Class for more information.

  4. 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.

  5. Add the following include statement to CDisplayDialogDoc.cpp (or CDisplayDialogApp.cpp) after the existing include statements:

    
    #include "TestDialog.h"
    
    
    
  6. Add the following code to OnViewTest to implement the function:

    
    CTestDialog testdlg;
    testdlg.DoModal();	
    
    
    

To display a modeless dialog box

  1. Do the first four steps to display a modal dialog box, except select the view class (CDisplayDialogView) in step 4.

  2. 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* m_pTestDlg;
      
      
      
  3. Edit DisplayDialogView.cpp:

    • Add the following include statement after the existing include statements:

      
      #include "TestDialog.h"
      
      
      
    • Add the following code to the constructor:

      
      m_pTestDlg = NULL;
      
      
      
    • Add the following code to the destructor:

      
      delete m_pTestDlg;
      
      
      
    • Add the following code to OnViewTest to implement the function:

      
      if (NULL == m_pTestDlg)
      {
         m_pTestDlg = new CTestDialog(this);
         m_pTestDlg->Create(CTestDialog::IDD, this);
      }
      m_pTestDlg->ShowWindow(SW_SHOW);	
      
      
      

Also, see the following Knowledge Base article:

  • Q251059 : HOWTO: Provide Your Own Window Class Name for an MFC Dialog Box

Community Additions

ADD
Show:
© 2014 Microsoft