MFC 對話框或視圖中需要顯示從文件讀取的多行文本數據,單行 CStatic 或單行 CEdit 無法滿足。
.rc),從工具箱拖入 Edit Control。Multi-line (ES_MULTILINE) —— 核心屬性Vertical Scroll (ES_AUTOVSCROLL | WS_VSCROLL) —— 內容超出自動顯示滾動條Read-only (ES_READONLY) —— 僅顯示不編輯時勾選Want Return (ES_WANTRETURN) —— 允許輸入換行(編輯模式需勾選)IDC_EDIT_LOG。在對話框類 (CMyDialog) 中添加控件變量:
// MyDialog.h
class CMyDialog : public CDialogEx {
// ...
CEdit m_editLog; // 控件變量
// 或 CString m_strLog; // 數據變量 (DDX_Text)
};
void CMyDialog::OnBnClickedBtnLoad() {
CFileDialog dlg(TRUE, _T("txt"), NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, _T("文本文件 (*.txt)|*.txt|所有文件|*.*||"));
if (dlg.DoModal() != IDOK) return;
CStdioFile file;
if (!file.Open(dlg.GetPathName(), CFile::modeRead | CFile::typeText)) {
AfxMessageBox(_T("打開文件失敗"));
return;
}
CString strLine, strAll;
while (file.ReadString(strLine)) {
strAll += strLine + _T("\r\n"); // 保留換行
}
file.Close();
// 方式一:控件變量直接設置 (推薦大文本)
m_editLog.SetWindowText(strAll);
m_editLog.LineScroll(m_editLog.GetLineCount()); // 滾動到底部
// 方式二:DDX 變量更新 (需 UpdateData(FALSE))
// m_strLog = strAll;
// UpdateData(FALSE);
}
若需富文本(顏色、字體、圖片),使用 CRichEditCtrl:
AfxInitRichEdit2() 在 InitInstance 中初始化。CRichEditCtrl。CHARFORMAT2 cf; cf.dwMask = CFM_COLOR; cf.crTextColor = RGB(0,0,255); m_richEdit.SetSelectionCharFormat(cf);ES_MULTILINE 已勾選,且文本包含 \r\n (Windows) 或 \n (Unix),MFC 支持兩者。SetWindowText 會重繪,超大文本建議分塊 ReplaceSel 或使用虛擬模式 EM_SETTEXTMODE。WS_VSCROLL 和 ES_AUTOVSCROLL,且控件高度足夠顯示多行。