MFC多文档应用程序同时显示两个视图
本文是对网络上各种资料进行了梳理,并在VisualC++6.0下进行了实验测试。
需要解决的问题如下:
1. 在MFC多文档应用程序中同时显示两个视图,其中一个视图显示电路原理图,另外一个显示仿真结果。
2. 两个视图需要同时显示,但是并非分割显示,而是通过切换(切换功能尚未实现)
在多文档应用程序中,视图类是由CMultiDocTemplate来负责管理的。自动生成的MFC框架中在C**App类的InitInstance()函数中,有以下的语句:
pDocTemplate= new CMultiDocTemplate(
IDR_**TYPE,
RUNTIME_CLASS(C**Doc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(C**View));
AddDocTemplate(pDocTemplate);
由于有两个视图需要显示,所以需要创建两个CMultiDocTemplate对象来管理,其中每个对象管理不同的View对象
为了方便在其他类中引用,我在C**App类中增
public:
CMultiDocTemplate* m_pTemplateDataView;
CMultiDocTemplate* m_pTemplateSchematicView;
然后在InitInstance()函数替换原有创建CMultiDocTemplate对象指针的语句,这里我的代码是:
m_pTemplateSchematicView = new CMultiDocTemplate(
IDR_TR_UWBTYPE,
RUNTIME_CLASS(CTR_UWBDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CTR_UWBView));
AddDocTemplate(m_pTemplateSchematicView);
m_pTemplateDataView = new CMultiDocTemplate(
IDR_TR_UWBTYPE,
RUNTIME_CLASS(CTR_UWBDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CDataView));
AddDocTemplate(m_pTemplateDataView);
而此时就有了两个视图,而MFC应用程序默认是只打开一个视图的,所以这时运行程序就会出现一个要求选择显示哪个视图的对话框
为了自动显示,我们需要重写C**App类的OnFileNew()函数
void CTR_UWBApp::OnFileNew(){
m_pTemplateSchematicView->OpenDocumentFile(NULL);
}
注意:该函数无法用classwizard添加,只能使用member function添加
根据MSDN2001,需要在C**App类的消息响应中添加一句话才能使该函数被响应
BEGIN_MESSAGE_MAP(CTR_UWBApp, CWinApp)
//{{AFX_MSG_MAP(CTR_UWBApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_FILE_NEW, OnFileNew)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP红色的是添加的那个句子。
注:MSDN2001:
CWinApp::OnFileNew
You must add an ON_COMMAND( ID_FILE_NEW, OnFileNew ) statement to your CWinApp class message map to enable this member function.
到目前为止,程序还只能显示一个view,另外一个view还没有被显示出来。
我们需要在C**Doc类中添加一些东西
在OnNewDocument()函数中我们添加如下
CTR_UWBApp* p_app = (CTR_UWBApp*)AfxGetApp();
CreateNewWindow(p_app->m_pTemplateDataView, this);
然后添加成员函数:
CFrameWnd* CTR_UWBDoc::CreateNewWindow(CDocTemplate *pTemplate, CDocument *pDocument){
ASSERT_VALID( pTemplate );
ASSERT_VALID( pDocument );
CFrameWnd* pFrame = pTemplate->CreateNewFrame(pDocument, NULL);
if( pFrame == NULL )
{
TRACE0( "Warning: failed to create new frame.\n" );
return NULL;
}
CRect rect;
GetClientRect(pFrame->m_hWnd,&rect);
pFrame->MoveWindow(0,0,rect.Width(),rect.Height());
ASSERT_KINDOF( CFrameWnd, pFrame );
pTemplate->InitialUpdateFrame( pFrame, pDocument );
return pFrame;
}
此时再运行则可以一下子显示两个view了,不是重叠的。但是原理图view显示不完整,因为不是全窗口大小。我把它设置了一下
在CChildFrame类中改写虚函数ActivateFrame(int nCmdShow) ,nCmdShow默认值就是-1
void CChildFrame::ActivateFrame(int nCmdShow) {
// TODO: Add your specialized code here and/or call the base class
if (nCmdShow == -1)
{nCmdShow = SW_SHOWMAXIMIZED;
}
CMDIChildWnd::ActivateFrame(nCmdShow);
}
这样显示的窗口就最大化了

浙公网安备 33010602011771号