头文件
class CViewCtrl
{
public:
CViewCtrl(void);
~CViewCtrl(void);
void SwitchToView(CRuntimeClass* pViewClass);
void SetCtrlParent(CWnd *pParent);
CObList m_listViews;// 所有创建视图的列表
protected:
CView* GetActiveView() const;
void SetActiveView(CView* pViewNew, BOOL bNotify = TRUE);
CView* GetNextView(POSITION& rPosition) const;
private:
CWnd *m_pParent;
CView* m_pViewActive;
};
cpp文件
CViewCtrl::CViewCtrl(void)
{
m_pParent = NULL;
m_pViewActive = NULL;
}
CViewCtrl::~CViewCtrl(void)
{
}
void CViewCtrl::SetCtrlParent(CWnd *pParent)
{
m_pParent = pParent;
}
void CViewCtrl::SwitchToView(CRuntimeClass* pViewClass)
{
CView* pView = NULL;
static UINT nID = AFX_IDW_PANE_FIRST + 1;
POSITION pos = m_listViews.GetHeadPosition(); //得到第一个视图位置
while(pView = GetNextView(pos))
{
if (pView->IsKindOf(pViewClass))
break;
};
if (pView == NULL)
{
CCreateContext *pContext;
pContext=new CCreateContext;
pContext->m_pNewViewClass=pViewClass;
pContext->m_pCurrentDoc=NULL;
pContext->m_pNewDocTemplate=NULL;
pContext->m_pLastView=NULL;
pContext->m_pCurrentFrame=NULL;
CWnd *pWnd=NULL;
//创建视图类对象,先从CObject*变换到CWnd*
pWnd=DYNAMIC_DOWNCAST(CWnd,pViewClass->CreateObject());
pWnd->Create(NULL,NULL,AFX_WS_DEFAULT_VIEW,CRect(10,10,100,100),m_pParent,nID,pContext);
delete pContext;
pView=DYNAMIC_DOWNCAST(CView,pWnd);
//将新视图添加到视图列表中
m_listViews.AddTail(pView);
nID++;
}
if (pView->IsKindOf(pViewClass))
{
CView* pOldView = NULL;
if(nID > AFX_IDW_PANE_FIRST + 2)
pOldView = GetActiveView();
if (pOldView != pView)
{
if (pOldView)
{
pOldView->ShowWindow(SW_HIDE);
}
pView->ShowWindow(SW_SHOW);
SetActiveView(pView);
pView->OnInitialUpdate();
}
}
}
CView* CViewCtrl::GetNextView(POSITION& rPosition) const
{
if (rPosition != NULL)
{
return (CView *)m_listViews.GetNext(rPosition);
}
else
{
return NULL;
}
}
CView* CViewCtrl::GetActiveView() const
{
ASSERT(m_pViewActive == NULL || m_pViewActive->IsKindOf(RUNTIME_CLASS(CView)));
return m_pViewActive;
}
void CViewCtrl::SetActiveView(CView *pViewNew, BOOL bNotify)
{
CView* pViewOld = m_pViewActive;
if (pViewNew == pViewOld)
return;
m_pViewActive = NULL;
if (pViewOld != NULL)
pViewOld->SendMessage(WM_ACTIVATE, WA_INACTIVE, 0);
m_pViewActive = pViewNew;
if (pViewNew != NULL && bNotify)
pViewNew->SendMessage(WM_ACTIVATE, WA_ACTIVE, 0);
}