MFC › 4. Dialogs and Controls
Modeless Dialogs and Property Sheets
Tabbed settings and non-blocking dialogs.
intermediate #mfc#modeless-dialog#cpropertysheet#cpropertypage#wizard#onapply#postncdestroy
Explanation
Modal vs modeless
Modal (DoModal) |
Modeless (Create) |
|
|---|---|---|
| Blocks the owner | yes, until closed | no: the user can keep working in the main window |
| Object lives | usually on the stack | on the heap (it must outlive the function) |
| Close | EndDialog via OnOK/OnCancel |
DestroyWindow |
| Typical use | settings, confirmation | Find dialog, tool palette |
For a modeless dialog:
m_pDlg = new CFindDlg(this); m_pDlg->Create(IDD_FIND, this); m_pDlg->ShowWindow(SW_SHOW);- Override
OnOKandOnCancelto callDestroyWindow()(the base versions callEndDialog, which is only valid for modal dialogs). - Override
PostNcDestroytodelete this, and clear your pointer so you can’t use it afterwards.
Property sheets (tabbed dialogs, as in the Windows Control Panel): a CPropertySheet holds several CPropertyPages, each a dialog template with the style Child + Thin border + Disabled.
sheet.AddPage(&page1)for each page;sheet.DoModal()(modal) orCreate(modeless).- The sheet adds OK, Cancel, Apply. Call
SetModified(TRUE)in a page when the user changes something to enable Apply;OnApply/OnOKis then called on the changed pages. - Wizard mode:
sheet.SetWizardMode(): pages become Back/Next/Finish steps. Control the buttons inOnSetActive()withGetParent()->SetWizardButtons(PSWIZB_NEXT)and validate inOnWizardNext()(return-1to stay on the page). - Pages are created lazily: a page’s controls exist only after it was first shown, so read data from member variables, not controls, for pages the user never visited.
Example
#include <afxwin.h>
#include <afxdlgs.h>
// ---- a modeless Find dialog
class CFindDlg : public CDialog {
public:
enum { IDD = IDD_FIND };
CFindDlg(CWnd* pOwner, CFindDlg** ppSelf) : CDialog(IDD, pOwner), m_ppSelf(ppSelf) {}
CString m_text;
protected:
CFindDlg** m_ppSelf; // owner's pointer, cleared when we die
void DoDataExchange(CDataExchange* pDX) override {
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_FIND_TEXT, m_text);
}
afx_msg void OnFindNext() {
UpdateData(TRUE); // controls -> m_text
GetOwner()->SendMessage(WM_COMMAND, ID_EDIT_FIND_NEXT); // tell the owner (loosely coupled)
}
void OnOK() override { DestroyWindow(); } // NOT CDialog::OnOK() (that is for modal)
void OnCancel() override { DestroyWindow(); }
void PostNcDestroy() override {
if (m_ppSelf) *m_ppSelf = nullptr; // owner sees it is gone
delete this; // heap object cleans itself up
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CFindDlg, CDialog)
ON_BN_CLICKED(IDC_FIND_NEXT, &CFindDlg::OnFindNext)
END_MESSAGE_MAP()
class COwnerFrame : public CFrameWnd {
CFindDlg* m_pFind = nullptr;
afx_msg void OnEditFind() {
if (m_pFind) { m_pFind->SetFocus(); return; } // already open
m_pFind = new CFindDlg(this, &m_pFind);
m_pFind->Create(CFindDlg::IDD, this);
m_pFind->ShowWindow(SW_SHOW);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(COwnerFrame, CFrameWnd)
ON_COMMAND(ID_EDIT_FIND, &COwnerFrame::OnEditFind)
END_MESSAGE_MAP()
// ---- property sheet with two pages
class CGeneralPage : public CPropertyPage {
public:
enum { IDD = IDD_PAGE_GENERAL };
CGeneralPage() : CPropertyPage(IDD), m_autoSave(FALSE) {}
BOOL m_autoSave;
protected:
void DoDataExchange(CDataExchange* pDX) override {
CPropertyPage::DoDataExchange(pDX);
DDX_Check(pDX, IDC_AUTOSAVE, m_autoSave);
}
afx_msg void OnAutoSaveClicked() { SetModified(TRUE); } // enables the Apply button
BOOL OnApply() override { // Apply or OK
UpdateData(TRUE);
// ... store the setting here ...
return CPropertyPage::OnApply();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CGeneralPage, CPropertyPage)
ON_BN_CLICKED(IDC_AUTOSAVE, &CGeneralPage::OnAutoSaveClicked)
END_MESSAGE_MAP()
class CAdvancedPage : public CPropertyPage {
public:
enum { IDD = IDD_PAGE_ADVANCED };
CAdvancedPage() : CPropertyPage(IDD) {}
};
void ShowOptions(CWnd* pParent) {
CPropertySheet sheet(_T("Options"), pParent);
CGeneralPage general;
CAdvancedPage advanced;
sheet.AddPage(&general);
sheet.AddPage(&advanced);
if (sheet.DoModal() == IDOK) {
// general.m_autoSave is valid if the page was ever shown
}
}
Common pitfalls
- A modeless dialog on the stack is destroyed when the function returns: allocate with
new. - Not overriding
OnOK/OnCancel: the base class callsEndDialog, which doesn’t close a modeless dialog (and asserts in debug). - Using the owner’s pointer after the dialog closed: set it to
nullptrinPostNcDestroy(as above). IsDialogMessagehandling: a modeless dialog in an app with a custom message loop needsPreTranslateMessageso Tab and Enter work. MFC’sCWinAppdoes this for you.- Reading controls of a property page the user hasn’t opened: they don’t exist yet (data members only).
- Property pages must have the correct template styles (Child, Disabled), otherwise the sheet renders them badly.
Win32 vs MFC
Win32 uses CreateDialog + IsDialogMessage in the message loop and PropertySheet(PROPSHEETHEADER*) with PROPSHEETPAGE arrays and callbacks. MFC’s classes wrap them. See Dialogs and DDX/DDV.
Exercises
1. Why must a modeless dialog override PostNcDestroy to delete this?
It was allocated with new and nobody else owns it. PostNcDestroy is the last call after the window is gone, which is the safe point to free the C++ object.