想写一个双色球的程序,为了每期的数据变化用图表表现出来,就要用到多视图。想着挺简单的,可是做起来还真给困住了。后来找了一些例子,还看了MFC的代码,想到MFC调用OnWindowNew函数时所做的动作,把代码拷过来,倒是能实现新生成一个视图,只是新生成的视图是空的,没有调用我自己的View类,百思不得其解啊(真笨啊,这点想了一上午都没想明白^_^)。后来还查MSDN,查到这样一句话:CreateNewFrame() creates both a frame and a view; not only a view. If, for some reason, CreateNewFrame() does not quite address your situation, the source code for CreateNewFrame() is quite useful to demonstrate the steps required to create frames and views. 看了以后没起太大反应,(还是英语不过关啊,看到思路了,愣是没反应过来,惭愧),后来在网上搜索,发现这句话的翻译(还是汉语好明白,呵呵),才醒悟过来,直查MFC中CreateNewFrame()函数的实现过程,把它搬过来改动了一点就可以了。
没有调用我自己的View类的原因,就是没有传过去,笨死了。现把代码放在这儿,以记录。
void CMainFrame::OnCreateView() //可以是菜单响应函数
{
// TODO: Add your command handler code here
CMDIChildWnd* pActiveChild = MDIGetActive();
CDocument* pDocument;
if (pActiveChild == NULL ||
(pDocument = pActiveChild->GetActiveDocument()) == NULL)
{
TRACE0("Warning: No active document for WindowNew command./n");
AfxMessageBox(AFX_IDP_COMMAND_FAILURE);
return; // command failed
}
// otherwise we have a new frame !
CDocTemplate* pTemplate = pDocument->GetDocTemplate();
ASSERT_VALID(pTemplate);
// 初始化创建上下文相关指针
CCreateContext newContext;
newContext.m_pNewViewClass = RUNTIME_CLASS(CMyFirstview);//要换成自己的View类
newContext.m_pCurrentDoc = pDocument;
newContext.m_pNewDocTemplate = pTemplate;
newContext.m_pLastView = NULL;
newContext.m_pCurrentFrame = pActiveChild;
///CreateNewFrame
CFrameWnd* pFrame = (CFrameWnd*)pActiveChild->CreateObject();//要用当前的FrameWnd生成
if (pFrame == NULL)
{
TRACE1("Warning: Dynamic create of frame %hs failed./n",
"CMyFirstView");
return ;
}
ASSERT_KINDOF(CFrameWnd, pFrame);
if (newContext.m_pNewViewClass == NULL)
TRACE0("Warning: creating frame with no default view./n");
// create new from resource
if (!pFrame->LoadFrame(IDR_MULTIVTYPE,
WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, // default frame styles
NULL, &newContext))
{
TRACE0("Warning: CDocTemplate couldn't create a frame./n");
// frame will be deleted in PostNcDestroy cleanup
return ;
}
pTemplate->InitialUpdateFrame(pFrame, pDocument);
}