Modeless Dialogs

Creating a modeless dialog in MFC is very easy, however, many MFC programmers seem to have problems with it.  Here I demonstrate the steps needed to be taken to create an MFC modeless dialog:

  1. Like creating any other dialog, first you need to insert a dialog resource into your project, and derive a class from CDialog, as you would do for a normal modal dialog.  I won’t describe this step more because I assume that every basic MFC text describes it well.
  2. Add a function named Create( ) to your dialog class, like this:
    // inside the .h file:

    class CMyDialog : public CDialog
    // ...
    BOOL Create(CWnd * pParent = NULL);

    // inside the .cpp file:

    BOOL CMyDialog::Create(CWnd * pParent)
    return CDialog::Create( CMyDialog::IDD, pParent );
  3. Make sure the CMyDialog constructor calls the default constructor of CDialog:

    CMyDialog::CMyDialog(CWnd * /*pParent*/)
    : CDialog()
    // ...

It’s that easy!  Now, to use your modeless dialog, you’ll need to consider the following points:

  1. You should call CMyDialog::Create( ) instead of CMyDialog::DoModal( ) to create a modeless dialog.
  2. When using a normal modal dialog, you create an instance of the dialog class on the stack, and call DoModal( ).  DoModal( ) would not return until the dialog is dismissed, and the dialog object can be safely destroyed.  But this is not the case with modeless dialogs.  Modeless dialogs should be created on the heap, because the Create( ) functions returns immediately after creating the dialog, and does not wait for the dialog to be dismissed, so if you call the dialog object on the stack, when the object goes out of scope, the destructor is called, and suddenly the dialog disappears!  Not what you would want of course.
  3. To dismiss a modeless dialog, CDialog::DestroyWindow( ) should be called.  Note that the default CDialog::OnOK( ) and CDialog::OnCancel( ) functions shouldn’t be called for a modeless dialog.
  4. Typically, a modeless dialog should be a "manager" object, which would be a class derived from CWnd or CView.  The manager object is responsible for creating and destroying the dialog object.  One usual way to do this is to register a custom window message, and make OnOK and OnCancel functions post that message to the manager window, and then the manager window is responsible for calling DestroyWindow.  If you are unclear with this, please download the demo application at the bottom of the article which demonstrates this technique.

 Download source code for this article

This article originally appeared on It’s been republished here, and may contain modifications from the original article.

Posted in Visual C++