首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

Visual C++ 多文檔模板 (Multi-DocTemplate) 實現 MDI 多文件類型支援

     編輯:VC 教學

場景

標準 MDI 僅支援單一文檔類型。若需同時處理「FIRST」與「SECOND」兩種資料格式、視圖截然不同 (如圖文 vs 聲音),必須建立兩套完整的 Doc/View/Frame 架構,並依副檔名自動選擇對應模板。

實作步驟

  1. InitInstance 註冊多模板:
    CMultiDocTemplate* pFirst = new CMultiDocTemplate(
        IDR_FIRSTTYPE,
        RUNTIME_CLASS(CFirstDoc), RUNTIME_CLASS(CFirstFrame), RUNTIME_CLASS(CFirstView));
    AddDocTemplate(pFirst);
    
    CMultiDocTemplate* pSecond = new CMultiDocTemplate(
        IDR_SECONDTYPE,
        RUNTIME_CLASS(CSecondDoc), RUNTIME_CLASS(CSecondFrame), RUNTIME_CLASS(CSecondView));
    AddDocTemplate(pSecond);
  2. 覆寫 CWinApp::OnFileOpen 依副檔名分派:
    void CMyApp::OnFileOpen() {
        CFileDialog dlg(TRUE);
        if (dlg.DoModal() != IDOK) return;
        CString path = dlg.GetPathName(), ext = dlg.GetFileExt();
        ext.MakeUpper();
    
        POSITION pos = GetFirstDocTemplatePosition();
        while (pos) {
            CDocTemplate* pTpl = GetNextDocTemplate(pos);
            CString name; pTpl->GetDocString(name, CDocTemplate::docName);
            if ((ext == "FIRST" && name == "First") ||
                (ext == "SECOND" && name == "Second")) {
                pTpl->OpenDocumentFile(path);
                return;
            }
        }
        AfxMessageBox("不支援的檔案類型");
    }

關鍵點

  • OpenDocumentFile 內部自動建立 Document、Frame、View 並送出初始化訊息。
  • 資源 ID (IDR_FIRSTTYPE) 需對應選單、圖示、工具列等資源。
  • 任意處可用 AfxGetApp() 取得應用程式指標,進而枚舉模板操作。

結語

多文檔模板機制讓單一 MDI 應用程式優雅支援多種異構文件類型,核心在於 AddDocTemplate 註冊與 OpenDocumentFile 分派。

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