我有一个 SDI MFC 应用程序,它的 CMainFrame 类派生自 CFrameWndEx。 该应用程序使用 CSingleDocument 模板连接文档/ View /框架。
我需要有另一个窗口,其中包含与主窗口 View 的同一文档相关的 View 内容。 将 CMainFrame 的另一个实例作为辅助窗口是否正确?
最佳答案
经过一些方法我得出了一个解决方案:
第一:
在 App 上有两个 CMainFrame 实例,其中第二个有一个 bool 字段来指示它是一个或另一个。这个 bool 值允许我只在第二个时跳过所有创建的创建,因为我只希望它是一个带有 View 的矩形。我向 CMainFrame 添加了一个特殊的公共(public)构造函数,它始终将引用的 bool 值设置为 true。
CMainFrame *pSecondFrame = new CMainFrame(TRUE /*dumb*/);
成功了,但是速度很慢。由于速度不够,第一个 MainFrame 的 View 完全无法使用。
第二个:
有一个同样从 CFrameWndEx 派生的 CSecondFrame,它的主体几乎没有任何东西。由于 IDR_MAINFRAME 什么都没有,我可以期望执行 LoadFrame(IDR_MAINFRAME) 并在 App 上有一个几乎空的框架。
CSecondFrame *pSecondFrame = new CSecondFrame();
成功了,但是速度很慢。由于速度不够,第一个 MainFrame 的 View 完全无法使用。
对于第一种和第二种方法,我必须添加一个新的 CreateContext,因为我不能重用大型机 View :
if (!pSecondFrame->LoadFrame(IDR_MAINFRAME))
return FALSE;
CMainFrame* pMainFrame=(CMainFrame*)::AfxGetMainWnd();
if (!pMainFrame)
return FALSE;
CMyView* pView=(CMyView*)(pMainFrame->GetActiveView());
if (!pView)
return FALSE;
CCreateContext context;
context.m_pCurrentDoc=pMainFrame->GetActiveDocument();
context.m_pNewViewClass= RUNTIME_CLASS(CMyView);
context.m_pLastView= pView;
context.m_pCurrentFrame = pSecondFrame;
pSecondFrame->CreateView(&context);
第三:
在 InitInstance 函数的开头,我有文档模板:
那么让我们来玩一玩它的 CreateNewFrame 方法: POSITION pos= pDocTemplate->GetFirstDocPosition();
//pFrameTemp attribution
CFrameWnd* pSecondFrame= pDocTemplate->CreateNewFrame(pDocTemplate->GetNextDoc(pos),pFrameTemp);
我为 pFrameTemp 尝试了不同的东西:NULL、CMainFrame、CSecondFrame。每次我得到一个框架,它是主体的副本,我不想要这个。
对于 CMainFrame 和 CSecondFrame 的情况,我试图显式调用它们的 Create( ...) 函数,但失败了,所以它们甚至没有传递它们的 OnCreate(...) 方法。 取而代之的是,我还尝试为这两种情况做一个 LoadFrame(IDR_MAINFRAME)。现在我将拥有三个框架:主框架、第二框架,它是主框架的副本,以及使用 LoadFrame 创建的完全空白的框架。
第四: 在看到他的 CreateNewFrame 方法基于它在模板上的框架而不是在其参数中传递的框架创建了一个新框架后,我决定尝试创建另外一个模板:
CSingleDocTemplate* pSecondDocTemplate;
pSecondDocTemplate2 = new CSingleDocTemplate(
MenuID,
RUNTIME_CLASS(CMyDoc),
RUNTIME_CLASS(CSecondFrame),//only the frame differs
RUNTIME_CLASS(CMyView));
AddDocTemplate(pSecondDocTemplate);
POSITION pos= pDocTemplate->GetFirstDocPosition();
CFrameWnd* pSecondFrame=pSecondDocTemplate->CreateNewFrame(pDocTemplate->GetNextDoc(pos), NULL);
请注意,我将第一个模板(而不是第二个)的文档作为参数提供给 CreateNewFrame。 这是我测试过的唯一有效且不会减慢 View 操作的解决方案。
看来我需要,对于我提出的每一个解决方案都要做
pSecondFrame->ShowWindow(SW_SHOW);
让窗口可见。
关于windows - Mfc多窗口同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8487840/