Windows 通過「文件關聯」將雙擊動作轉為命令行啟動:YourApp.exe "C:\path\to\file.txt"。MFC 應用需在 InitInstance 解析命令行並加載文件。
BOOL CMyApp::InitInstance() {
// ... 標準初始化 ...
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo); // 解析命令行
// 必須先調用 ProcessShellCommand 以建立文檔/視圖
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// 隨後可獲取命令行參數(雙擊文件路徑)
LPTSTR cmdLine = ::GetCommandLine();
int argc = 0;
LPWSTR* argv = ::CommandLineToArgvW(cmdLine, &argc);
if (argc > 1) {
CString filePath = argv[1]; // 第二個參數為文件路徑
// 這裡可調用文檔的 LoadFile(filePath)
// 注意:若 ProcessShellCommand 已處理 FileOpen,這裡可能重複,需視邏輯而定
}
::LocalFree(argv);
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
ParseCommandLine 填充 cmdInfo.m_strFileName(文件路徑)和 cmdInfo.m_nShellCommand(CCommandLineInfo::FileOpen)。ProcessShellCommand 會自動調用文檔的 OnOpenDocument 或 OnNewDocument,這就是雙擊打開的核心入口。BOOL OnOpenDocument(LPCTSTR lpszPathName) 實現讀取邏輯。BOOL CMyDoc::OnOpenDocument(LPCTSTR lpszPathName) {
if (!CDocument::OnOpenDocument(lpszPathName))
return FALSE;
CFile file(lpszPathName, CFile::modeRead | CFile::shareDenyWrite);
CArchive ar(&file, CFile::load);
// 讀取內容到成員變量
ar >> m_strContent;
ar.Close();
UpdateAllViews(NULL); // 通知視圖刷新
return TRUE;
}
[HKEY_CLASSES_ROOT\.myext]
@="MyApp.Document"
[HKEY_CLASSES_ROOT\MyApp.Document\shell\open\command]
@="\"C:\\Path\\To\\MyApp.exe\" \"%1\""
MFC 實現「雙擊文件打開」:文件關聯註冊 → 命令行參數傳遞 → InitInstance 中 ParseCommandLine + ProcessShellCommand → 文檔 OnOpenDocument 讀取。掌握這條鏈路即可像記事本一樣無縫打開文件。