將「讀取文件並顯示」邏輯封裝為獨立函數,命令行啟動與菜單打開均調用該函數。
BOOL CMyDoc::LoadFile(const CString& path) {
CFile file;
if (!file.Open(path, CFile::modeRead | CFile::shareDenyWrite))
return FALSE;
CArchive ar(&file, CFile::load);
CString content;
ar.ReadString(content); // 或循環讀取
ar.Close();
file.Close();
// 更新視圖
POSITION pos = GetFirstViewPosition();
while (pos) {
CView* pView = GetNextView(pos);
if (pView->IsKindOf(RUNTIME_CLASS(CMyView))) {
((CMyView*)pView)->SetEditText(content);
}
}
return TRUE;
}
在 CWinApp::InitInstance 中:
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileOpen) {
// cmdInfo.m_strFileName 即為雙擊文件傳入的路徑
if (!pDoc->LoadFile(cmdInfo.m_strFileName))
return FALSE;
}
if (!ProcessShellCommand(cmdInfo)) return FALSE;
void CMyDoc::OnFileOpen() {
CFileDialog dlg(TRUE, _T("txt"), NULL, OFN_HIDEREADONLY, _T("文本文件|*.txt||"));
if (dlg.DoModal() == IDOK) {
LoadFile(dlg.GetPathName());
}
}
CCommandLineInfo 自動解析命令行參數,m_nShellCommand == FileOpen 表示雙擊文件關聯啟動。LoadFile 服務於命令行、菜單、拖放等多種入口。MFC 記事本直接打開文件的關鍵在於 命令行參數解析 + 文檔讀取邏輯復用。將核心讀取封裝為 LoadFile,實現「一處實現、多處調用」。