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:
- 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.
- 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 );
Make sure the CMyDialog constructor calls the default constructor of CDialog:
CMyDialog::CMyDialog(CWnd * /*pParent*/)
It’s that easy! Now, to use your modeless dialog, you’ll need to consider the following points:
- You should call CMyDialog::Create( ) instead of CMyDialog::DoModal( ) to create a modeless dialog.
- 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.
- 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.
- 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.