上面给出了通过CDocTemplate 的构造函数将文档、视图、和框架关联起来,但是有时候我们并不想创建一个新的文档模版,我们只是想给同一个数据提供不同的结果显示,或者说是为同一个文档添加一个新的视图,并提供他们之间的一个切换。还有一种可能就是我们本来不是一个文档视图结构支持的程序,想为视图添加一个文档,更好进行业务逻辑和表示层的一个分离。第一种方法的实现方法:
Step 1:使用 VC 6.0 新建一个 Project ,命名为: MultiView 。除选择单文档属性外,一切使用“默认”方式。于是你可以获得五个类: CMainFrame , CMultiViewApp , CMultiViewDoc ,CMultiViewView ,和 CAboutDlg ;
Step 2:新建一个新的视图 View ,添加一个新的 MFC Class ( Insert - >New Class ),基类为CView (或者 CView 的派生子类,如 CEditView 等)。类的名字为 CAnotherView ,这就是新的视图;并为 CAnotherView 添加 GetDocument 的实现:
CMultiViewDoc* CAnotherView::GetDocument()
{
return (CMultiViewDoc*)m_pDocument;
}
Step 3:在 CMultiViewApp 添加成员变量记录这两个视图:
private:
CView* m_pFirstView;
CView* m_pAnotherView;
给程序菜单IDR_MAINFRAME 添加一个菜单项目“视图”,该菜单项有两个子菜单“视图一”和“视图二”,添加相应函数( void CMultiViewApp :: OnShowFirstview ()和 void CMultiViewApp ::OnShowSecondview ());
Step 4 :创建新的视图:在 BOOL CMultiViewApp :: InitInstance () 中添加代码:
…….
// 创建一个新的视图
CView* m_pActiveView = ((CFrameWnd*)m_pMainWnd)->GetActiveView();
m_pFirstView = m_pActiveView;
m_pAnotherView = new CAnotherView();
// 文档和视图关联
CDocument* m_pDoc = ((CFrameWnd*)m_pMainWnd)->GetActiveDocument();
CCreateContext context;
context.m_pCurrentDoc = m_pDoc;
// 创建视图
UINT m_IDFORANOTHERVIEW = AFX_IDW_PANE_FIRST + 1;
CRect rect;
m_pAnotherView->Create(NULL,NULL,WS_CHILD,rect,m_pMainWnd,
m_IDFORANOTHERVIEW,&context);
……
Step 5:现在已经创建了视图,并且都和文档关联起来了。现在要作的就是视图间的转换。在void CMultiViewApp :: OnShowFirstview ()中添加实现代码:
void CMultiViewApp::OnShowFirstview()
{
// TODO: Add your command handler code here
UINT temp = ::GetWindowLong(m_pAnotherView->m_hWnd, GWL_ID);
::SetWindowLong(m_pAnotherView->m_hWnd, GWL_ID, ::GetWindowLong(m_pFirstView->m_hWnd, GWL_ID));
::SetWindowLong(m_pFirstView->m_hWnd, GWL_ID, temp);
m_pAnotherView->ShowWindow(SW_HIDE);
m_pFirstView->ShowWindow(SW_SHOW);
((CFrameWnd*)m_pMainWnd)->SetActiveView(m_pFirstView);
((CFrameWnd*) m_pMainWnd)->RecalcLayout();
m_pFirstView->Invalidate();
}
在 voidCMultiViewApp :: OnShowSecondview ()中添加实现代码:
void CMultiViewApp::OnShowSecondview()
{
// TODO: Add your command handler code here
UINT temp = ::GetWindowLong(m_pAnotherView->m_hWnd, GWL_ID);
::SetWindowLong(m_pAnotherView->m_hWnd, GWL_ID, ::GetWindowLong(m_pFirstView->m_hWnd, GWL_ID));
::SetWindowLong(m_pFirstView->m_hWnd, GWL_ID, temp);
m_pFirstView->ShowWindow(SW_HIDE);
m_pAnotherView->ShowWindow(SW_SHOW);
((CFrameWnd*)m_pMainWnd)->SetActiveView(m_pAnotherView);
((CFrameWnd*) m_pMainWnd)->RecalcLayout();
m_pAnotherView->Invalidate();
}
Step 6:为了演示,这里将不同的视图给予一个标记,在 CMultiViewView 和 CAnotherView 的OnDraw 方法中分别添加以下代码:
pDC->TextOut(400,300,"First View");
pDC->TextOut(400,320,pDoc->GetTitle());
和
pDC->TextOut(400,300,"Another View");
pDC->TextOut(400,320,pDoc->GetTitle());
至此就大功告成了,但是实现过程中有几点说明:
1) 实现中由于使用到相关的类,因此在必要的地方要 include 相关的头文件,这里省略;CAnotherView 的默认构造函数是 Protected 的,需要将其改为 Public ,或者提供一个产生CAnotherView 对象的方法(因要创建视图对象);
2) 这里给出的是一个示例代码,实际开发中可以通过参考实现获得自己想要实现的具体应用情况(例如视图类的不同、数量不同,更重要的还有业务逻辑的不同实现等);
免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。