MFC › 4. Dialogs and Controls
Common Dialogs
File, color, font and print dialogs.
Explanation
Windows supplies standard dialogs, wrapped by MFC (header <afxdlgs.h>):
| Class | Purpose |
|---|---|
CFileDialog |
Open / Save As |
CFolderPickerDialog |
choose a folder (Vista-style) |
CColorDialog |
pick a color |
CFontDialog |
pick a font |
CPrintDialog |
printer choice, copies, page range |
CFindReplaceDialog |
modeless Find/Replace (notifies the owner by a registered message) |
AfxMessageBox |
simple message / question box with buttons |
All except CFindReplaceDialog are used the same way: construct, DoModal(), and if the result is IDOK read the answer.
CFileDialog constructor: CFileDialog(bOpen, defaultExt, defaultFileName, flags, filter, parent). The filter is "Description|pattern|Description|pattern||" (pairs separated by |, terminated by ||). Common flags: OFN_FILEMUSTEXIST, OFN_OVERWRITEPROMPT, OFN_HIDEREADONLY, OFN_ALLOWMULTISELECT. Read results with GetPathName, GetFileName, GetFileExt, GetFolderPath; for multi-select iterate GetStartPosition / GetNextPathName.
AfxMessageBox(text, MB_YESNOCANCEL | MB_ICONQUESTION) returns IDYES, IDNO, IDCANCEL, … Prefer the string-table overload (AfxMessageBox(IDS_CONFIRM)) for localizable text.
Example
#include <afxwin.h>
#include <afxdlgs.h>
class CMainFrame : public CFrameWnd {
protected:
COLORREF m_bkColor = RGB(255, 255, 255);
LOGFONT m_logFont = {};
afx_msg void OnOpenFile() {
CFileDialog dlg(TRUE, _T("txt"), nullptr,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT,
_T("Text files (*.txt)|*.txt|All files (*.*)|*.*||"), this);
if (dlg.DoModal() != IDOK) return; // user cancelled
for (POSITION pos = dlg.GetStartPosition(); pos; ) {
CString path = dlg.GetNextPathName(pos); // one entry per selected file
AfxMessageBox(path);
}
}
afx_msg void OnSaveAs() {
CFileDialog dlg(FALSE, _T("txt"), _T("untitled"),
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("Text files (*.txt)|*.txt||"), this);
if (dlg.DoModal() == IDOK)
AfxMessageBox(_T("Saving to ") + dlg.GetPathName() + _T(" (ext: ") + dlg.GetFileExt() + _T(")"));
}
afx_msg void OnPickFolder() {
CFolderPickerDialog dlg(nullptr, 0, this);
if (dlg.DoModal() == IDOK) AfxMessageBox(dlg.GetPathName());
}
afx_msg void OnPickColor() {
CColorDialog dlg(m_bkColor, CC_FULLOPEN, this);
if (dlg.DoModal() == IDOK) {
m_bkColor = dlg.GetColor();
Invalidate();
}
}
afx_msg void OnPickFont() {
CFontDialog dlg(&m_logFont); // initial values in, results out
if (dlg.DoModal() == IDOK) {
dlg.GetCurrentFont(&m_logFont);
AfxMessageBox(dlg.GetFaceName());
}
}
afx_msg void OnQuit() {
if (AfxMessageBox(_T("Exit the program?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
DestroyWindow();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_COMMAND(ID_FILE_OPEN, &CMainFrame::OnOpenFile)
ON_COMMAND(ID_FILE_SAVE_AS, &CMainFrame::OnSaveAs)
ON_COMMAND(ID_PICK_FOLDER, &CMainFrame::OnPickFolder)
ON_COMMAND(ID_PICK_COLOR, &CMainFrame::OnPickColor)
ON_COMMAND(ID_PICK_FONT, &CMainFrame::OnPickFont)
ON_COMMAND(ID_APP_EXIT, &CMainFrame::OnQuit)
END_MESSAGE_MAP()
Common pitfalls
- Forgetting the closing
||of the filter string makes the dialog show a single empty filter or garbage. GetPathName()is only valid afterDoModalreturnedIDOK.OFN_ALLOWMULTISELECThas a default buffer of about 260 characters; with many files the dialog returns an error. Increasedlg.m_ofn.lpstrFile/nMaxFilewith your own buffer.- Using the old-style file dialog on a project that sets
OFN_EXPLORERincorrectly shows the legacy UI; use the defaults. CFontDialogneedsLOGFONTinitialized to zero. Create aCFontfrom the result withfont.CreateFontIndirect(&m_logFont)and delete it later.- Showing a dialog from a worker thread is not allowed: dialogs must be created on a UI thread.
- A
CFindReplaceDialogis modeless: it must be created withnewandCreate()(see Modeless Dialogs and Property Sheets).
Win32 vs MFC
Win32 uses GetOpenFileName(&OPENFILENAME) with a hand-built structure and a double-NUL-terminated filter string; the newer COM IFileOpenDialog is the modern API. MFC hides the structure but exposes it as dlg.m_ofn for advanced settings.
Exercises
1. Write the filter string for "Images" (*.png, *.jpg) and "All files".
_T("Images (*.png;*.jpg)|*.png;*.jpg|All files (*.*)|*.*||")