Windows 提供標準通用對話框,MFC 封裝為 `CFileDialog`、`CColorDialog`、`CFontDialog`。無需衍生新類,直接建構、呼叫 `DoModal()`,關閉後透過成員函數取得使用者選擇。本文詳細說明三大對話框的建構參數、回傳值獲取與進階選項。
CFileDialog(
BOOL bOpenFileDialog, // TRUE=開啟, FALSE=另存新檔
LPCTSTR lpszDefExt = NULL, // 預設副檔名
LPCTSTR lpszFileName = NULL, // 預設檔名
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
LPCTSTR lpszFilter = NULL, // 檔案類型過濾器
CWnd* pParentWnd = NULL // 父視窗
);
過濾器字串格式:
"文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*||"
「說明|模式」對用 `|` 分隔,同類多模式用 `;`,結尾雙 `||`。
CColorDialog(COLORREF clrInit = 0, DWORD dwFlags = 0, CWnd* pParentWnd = NULL);
CFontDialog(LPLOGFONT lplfInitial = NULL,
DWORD dwFlags = CF_EFFECTS | CF_SCREENFONTS,
CDC* pdcPrinter = NULL, CWnd* pParentWnd = NULL);
void CMyView::OnFileOpen() {
CFileDialog dlg(TRUE, _T("txt"), NULL, OFN_FILEMUSTEXIST,
_T("文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*||"));
if (dlg.DoModal() == IDOK) {
CString path = dlg.GetPathName();
// 讀取檔案...
}
}
void CMyView::OnFormatFont() {
LOGFONT lf;
GetFont()->GetLogFont(&lf); // 目前字型作為預設
CFontDialog dlg(&lf, CF_EFFECTS | CF_SCREENFONTS);
if (dlg.DoModal() == IDOK) {
dlg.GetCurrentFont(&lf);
CFont newFont;
newFont.CreateFontIndirect(&lf);
SetFont(&newFont); // 套用至視窗/控制項
Invalidate();
}
}