# MDI程序系统框架单文档对应多视图 切换 创建实现过程。

1。原来系统采用了创建多个文档模板，当切换不同的视图显示的时候 ，调用响应的文档模板指针，来生成视图。

<P nd="1">To fully understand what follows, some previous knowledge is required,
namely how MFC creates documents, frame windows and views using document
templates and how their relationship is maintained in the program. A <A
href="http://www.codeproject.com/docview/ReplacingView.asp">previous article</A>
showing how to replace views in non-OLE applications is a recommended
<P nd="2">First of all, let's understand how the framework creates OLE frames.
When a <A class=iAs
style="FONT-WEIGHT: normal; FONT-SIZE: 100%; PADDING-BOTTOM: 1px; COLOR: darkgreen; BORDER-BOTTOM: darkgreen 0.07em solid; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline"
href="#" target=_blank itxtdid="3675733">server</A> object is inserted in a
container, a document, a frame window and a view contained within it (or
multiple views, if it is a splitter) are first constructed, following common
document-template procedures. After that, in response to the <CODE
nd="3">OLEIVERB_SHOW</CODE> OLE verb, the <CODE
nd="4">COleServerDoc::ActivateInPlace</CODE> function is called. If there is no
previous OLE frame (i.e. it is the first time it will be activated), the OLE
frame is created, calling the <CODE
nd="5">COleServerDoc::CreateInPlaceFrame</CODE> function. Here, not only the OLE
frame is created (using the <CODE nd="6">CDocTemplate::CreateOleFrame</CODE>
function), but also the view in the previously constructed frame window is
"connected" to the newly created OLE frame. If the original frame was a
splitter, then the view in the first pane is used. The "connection" process
consists on changing the view's parent window to the new frame. It is performed
calling the <CODE nd="7">COleServerDoc::ConnectView</CODE> function. The active
view on the original frame window is kept (using the <CODE
nd="8">m_pActiveView</CODE> member), because some controls continue to send
messages should be handled in the original frame window. Once the OLE frame is
created and a view is "connected" to it, then it is activated.</P>
<P nd="9">Now, if we want to replace a view in an OLE frame, we have to replace
it in 2 frame windows: the OLE frame and the original frame. The current active
view should be destroyed, a new view should be created within the original frame
and be later connected to the OLE frame. The active views should be set to <CODE
nd="10">NULL</CODE> first, so no Windows message could be sent by the framework
to a non-valid view stored in the <CODE nd="11">m_pActiveView</CODE> member of
the frame windows.</P>
<P nd="12">To perform this, we need a method in our document class, which should
receive the new view type as a parameter and return a success flag. The
advantage of having this method in the document class becomes obvious when there
are several document types each of which can have different view types. Note
that the document should be a <CODE nd="13">COleServerDoc</CODE> descendant.
This is how it is done:</P>
<DIV class=precollapse id=premain0 style="WIDTH: 100%"><IMG id=preimg0
style="CURSOR: hand" height=9 src="http://www.codeproject.com/images/minus.gif"
width=9 preid="0"> Collapse</DIV><PRE id=pre0 style="MARGIN-TOP: 0px" nd="15">BOOL CMyDoc::InPlaceSwitchToView ( CRuntimeClass *pNewViewClass )
{
// The original parent window is saved in m_pOrigParent.
CFrameWnd* pFrame = (CFrameWnd *)m_pOrigParent;

// Get the active view.
View* pOldActiveView = m_pInPlaceFrame->GetActiveView();

// If we're already displaying this kind of view, no need to go further.
if (pOldActiveView->IsKindOf(pNewViewClass))
return TRUE;

// No currently active views in either frame
pFrame->SetActiveView(NULL);
m_pInPlaceFrame->SetActiveView(NULL);

// Set flag so that document will not be deleted when view is destroyed.
BOOL bAutoDelete = m_bAutoDelete;
m_bAutoDelete = FALSE;

// Delete existing view
pOldActiveView->DestroyWindow();

// restore flag
m_bAutoDelete = bAutoDelete;

// Create new view.
CView* pNewView = (CView *)pNewViewClass->CreateObject();
if (pNewView == NULL)
{
TRACE1("Warning: Dynamic create of view type %Fs failed/n",
pNewViewClass->m_lpszClassName);
return FALSE;
}

// Draw new view.
CCreateContext context;
context.m_pNewViewClass = pNewViewClass;
context.m_pCurrentDoc = this;
context.m_pNewDocTemplate = NULL;
context.m_pLastView = NULL;
context.m_pCurrentFrame = pFrame;
if (!pNewView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0),
pFrame, AFX_IDW_PANE_FIRST, &context))
{
TRACE0("Warning: couldn't create view for frame/n");
delete pNewView;
return FALSE;
}

// Keep the view active in the original frame
pFrame->SetActiveView(pNewView);

// Connect the view to the OLE frame
ConnectView(m_pInPlaceFrame, pNewView);
pNewView->ModifyStyleEx(WS_EX_CLIENTEDGE, 0, SWP_DRAWFRAME);
pNewView->SendMessage(WM_INITIALUPDATE, 0, 0);

// WM_INITIALUPDATE is defined in afxpriv.h
pNewView->UpdateWindow();

return TRUE;
}</PRE>

## Introduction

Sometimes the way a document is being visualized needs to be significantly changed. For example, in PowerPoint, you can see the slides in a WYSIWYG form or view only the text in a text edit window. In the MFC world, one can find an amazingly large quantity of programs that implement this behavior defining one CView descendant and making it responsible for all visualization changes. This path has several disadvantages:

• Big, difficult to manage class definition file.
• Diminished reusability: you could reuse one big CView descendant or nothing.
• Hard to maintain (what if you want to modify or add a new "look" to the document?).
• Wasted memory: some variables (objects) will exist in memory and won’t be used.

For an application using the MFC document-view architecture, it is more appropriate to define different view classes and switch between them when necessary. This shall overcome all the disadvantages listed before. There probably will be some features common to all views for the same type of document, so it is a good idea to have a direct CView descendant that implement all the functionality common to all view types. The views used by the document should be descendants of this class ("grandchildren" of CView).

The code needed to implement view switching depends on the frame window containing the view. There are three common cases: the view is contained within a CFrameWnd (SDI application), the view is contained within a CMDIChildWnd (MDI application) and the view is a pane of a splitter window, either in SDI or MDI applications. In all cases what we need is a method in our document class to switch to the desired view. This method should receive the new view type as a parameter and return a success flag. The advantage of having this method in the document class becomes obvious when there are several document types each of which can have different view types. Lets start with an SDI application that doesn’t have splitters:

Collapse
BOOL CMyDocument::SwitchToView(CRuntimeClass* pNewViewClass)
{
CFrameWnd* pMainWnd = (CFrameWnd*)AfxGetMainWnd();
CView* pOldActiveView = pMainWnd->GetActiveView();

// If we're already displaying this kind of view, no need to go further.
if (pOldActiveView->IsKindOf(pNewViewClass))
return TRUE;

// Set the child window ID of the active view to AFX_IDW_PANE_FIRST.
// This is necessary so that CFrameWnd::RecalcLayout will allocate
// this "first pane" to that portion of the frame window's client
// area not allocated to control bars.  Set the child ID of
// the previously active view to some other ID.
::SetWindowLong(pOldActiveView->m_hWnd, GWL_ID, 0);

// create the new view
CCreateContext context;
context.m_pNewViewClass = pNewViewClass;
context.m_pCurrentDoc = this;
CView* pNewView = STATIC_DOWNCAST(CView, pMainWnd->CreateView(&context));
if (pNewView != NULL)
{
// the new view is there, but invisible and not active...
pNewView->ShowWindow(SW_SHOW);
pNewView->OnInitialUpdate();
pMainWnd->SetActiveView(pNewView);
pMainWnd->RecalcLayout();

// destroy the old view...
pOldActiveView->DestroyWindow();
return TRUE;
}

return FALSE;
}



In the case of an MDI application (again without splitters):

Collapse
BOOL CMyDocument::SwitchToView(CRuntimeClass* pNewViewClass)
{
CMDIFrameWnd* pMainWnd = (CMDIFrameWnd*)AfxGetMainWnd();

// Get the active MDI child window.
CMDIChildWnd* pChild = (CMDIChildWnd*)pMainWnd->MDIGetActive();

// Get the active view attached to the active MDI child window.
CView* pOldActiveView = pChild->GetActiveView();

// If we're already displaying this kind of view, no need to go further.
if (pOldActiveView->IsKindOf(pNewViewClass))
return TRUE;

// Set flag so that document will not be deleted when view is destroyed.
BOOL bAutoDelete = m_bAutoDelete;
m_bAutoDelete = FALSE;

// Delete existing view
pOldActiveView->DestroyWindow();

// restore flag
m_bAutoDelete = bAutoDelete;

// Create new view.
CView* pNewView = (CView *)pNewViewClass->CreateObject();
if (pNewView == NULL)
{
TRACE1("Warning: Dynamic create of view type %Fs failed/n",
pNewViewClass->m_lpszClassName);
return FALSE;
}

// Draw new view.
CCreateContext context;
context.m_pNewViewClass = pNewViewClass;
context.m_pCurrentDoc = this;
context.m_pNewDocTemplate = NULL;
context.m_pLastView = NULL;
context.m_pCurrentFrame = pChild;
if (!pNewView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
CRect(0, 0, 0, 0), pChild, AFX_IDW_PANE_FIRST, &context))
{
TRACE0("Warning: couldn't create view for frame/n");
delete pNewView;
return FALSE;
}

// WM_INITIALUPDATE is defined in afxpriv.h
pNewView->SendMessage(WM_INITIALUPDATE, 0, 0);
pChild->RecalcLayout();
pNewView->UpdateWindow();
pChild->SetActiveView(pNewView);
return TRUE;
}


When the view to replace is a pane of a splitter window, there is also a small difference between SDI and MDI applications, related to the retrieval of the current active view. In the method below you must comment out what you don’t need depending on your application type:

Collapse
BOOL CMyDocument::SwitchToView(CRuntimeClass* pNewViewClass)
{
/* Uncomment this if this is a SDI application
CFrameWnd* pMainWnd = (CFrameWnd*)AfxGetMainWnd();
CView* pOldActiveView = pMainWnd->GetActiveView();
*/

/* Uncomment this if this a MDI application
CMDIFrameWnd* pMainWnd = (CMDIFrameWnd*)AfxGetMainWnd();

// Get the active MDI child window.
CMDIChildWnd* pChild = (CMDIChildWnd*)pMainWnd->MDIGetActive();

// Get the active view attached to the active MDI child window.
CView* pOldActiveView = pChild->GetActiveView();
*/

// If we're already displaying this kind of view, no need to go further.
if (pOldActiveView->IsKindOf(pNewViewClass))
return TRUE;

CSplitterWnd* pSplitter = (CSplitterWnd *)pOldActiveView->GetParent();
int row, col;
ASSERT(pSplitter->IsChildPane(pOldActiveView, row, col));
CRect viewrect;
pOldActiveView->GetWindowRect(&viewrect);

// set flag so that document will not be deleted when view is destroyed
m_bAutoDelete = FALSE;

// Delete existing view
pOldActiveView->DestroyWindow();

// set flag back to default
m_bAutoDelete = TRUE;

// Create new view
CCreateContext context;
context.m_pNewViewClass = pNewViewClass;
context.m_pCurrentDoc = this;
context.m_pNewDocTemplate = NULL;
context.m_pLastView = NULL;
context.m_pCurrentFrame = NULL;
if (!pSplitter->CreateView(row, col, pNewViewClass, viewrect.Size(),
&context))
return FALSE;

// Set active
CView* pNewView = (CView *)pSplitter->GetPane(row, col);
pSplitter->GetParentFrame()->SetActiveView(pNewView);

pSplitter->RecalcLayout();
pNewView->SendMessage(WM_PAINT);
return TRUE;
}


Now that we have a method in our document class that will replace the current view, lets use it. The new view type should be decided (in response to a menu selection, for instance), and the function must be called as follows:

   CRuntimeClass* pNewViewClass = RUNTIME_CLASS(CMyView);
if (!SwitchToView(pNewViewClass))
// failed
else
// succeeded


One final word to the class wizard fans. When you have a descendant of a CView descendant, the class wizard won’t allow you to edit this class. To change this behavior, change all class wizard comments replacing the name of your direct CView descendant with CView. Class wizard will now work.

07-22 3554

03-22 1061
11-14 1231
10-18 352
01-17 701
05-21 1万+
10-17 4747