MDI应用中如何检测Doc/View实例并确保仅存在一个?
MDI应用中确保单一Doc/View实例的实现方法
你当前的问题出在先关闭所有文档再强制创建新实例,不管CloseAllDocuments参数是TRUE还是FALSE,调用OpenDocumentFile(NULL)都会生成新文档。正确的思路应该是先检查目标文档是否已经存在,存在就激活它,不存在再创建新实例。
以下是修改后的代码,实现单一实例的逻辑:
void App::OnDocumentA() { CDocTemplate* pDocTemplate = nullptr; POSITION pos = GetFirstDocTemplatePosition(); // 遍历所有文档模板,找到名为"Stories"的模板 while (pos != nullptr) { pDocTemplate = GetNextDocTemplate(pos); CString strDocName; pDocTemplate->GetDocString(strDocName, CDocTemplate::docName); if (strDocName == _T("Stories")) { // 检查该模板下是否已有文档实例 POSITION docPos = pDocTemplate->GetFirstDocPosition(); if (docPos != nullptr) { // 获取已存在的文档 CDocument* pExistingDoc = pDocTemplate->GetNextDoc(docPos); // 激活该文档的第一个视图窗口 POSITION viewPos = pExistingDoc->GetFirstViewPosition(); if (viewPos != nullptr) { CView* pView = pExistingDoc->GetNextView(viewPos); CMDIChildWnd* pChildWnd = (CMDIChildWnd*)pView->GetParentFrame(); if (pChildWnd != nullptr) { // 激活子窗口并置于顶层 pChildWnd->ActivateFrame(SW_SHOW); return; // 已有实例,直接返回,无需创建新的 } } } // 没有找到已存在的实例,创建新文档 pDocTemplate->OpenDocumentFile(nullptr); break; } } }
代码说明:
- 先遍历文档模板找到目标模板("Stories")
- 检查该模板下是否有已存在的文档实例:通过
GetFirstDocPosition和GetNextDoc获取现有文档 - 如果存在文档实例,找到对应的视图窗口,激活该MDI子窗口,直接返回,不创建新实例
- 如果没有现有实例,才调用
OpenDocumentFile(nullptr)创建新文档
这样就能确保任何时候"Stories"文档只有一个实例,避免重复创建。
内容的提问来源于stack exchange,提问作者Patrick Smith
相关产品推荐
相关产品推荐

