首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

MFC 實現像記事本一樣雙擊文件關聯啟動並打開

     編輯:程式設計疑難解答

核心機制

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;
}

關鍵點解析

  1. ParseCommandLine 填充 cmdInfo.m_strFileName(文件路徑)和 cmdInfo.m_nShellCommand(CCommandLineInfo::FileOpen)。
  2. ProcessShellCommand 會自動調用文檔的 OnOpenDocument 或 OnNewDocument,這就是雙擊打開的核心入口。
  3. 文檔類需重寫 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 讀取。掌握這條鏈路即可像記事本一樣無縫打開文件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved