標準 MDI 僅支援單一文檔類型。若需同時處理「FIRST」與「SECOND」兩種資料格式、視圖截然不同 (如圖文 vs 聲音),必須建立兩套完整的 Doc/View/Frame 架構,並依副檔名自動選擇對應模板。
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);
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 並送出初始化訊息。IDR_FIRSTTYPE) 需對應選單、圖示、工具列等資源。AfxGetApp() 取得應用程式指標,進而枚舉模板操作。多文檔模板機制讓單一 MDI 應用程式優雅支援多種異構文件類型,核心在於 AddDocTemplate 註冊與 OpenDocumentFile 分派。