1. 首先,在程序中添加对话框资源,使用向导为对话框添加类。
2. 为了使得视图创建在指定的区域,在对话框上放一个静态文本控件,资源ID为IDC_STATIC_VIEW。
3. 在OnInitDialog 函数中添加以下代码:
// 方法一:
UINT TargetCtrlID = IDC_STATIC_VIEW;
CWnd *pWnd = this->GetDlgItem(TargetCtrlID);
CRect RectTargetCtrl;
pWnd->GetWindowRect(RectTargetCtrl);
pWnd->DestroyWindow();
this->ScreenToClient(RectTargetCtrl);
m_picView = (CPictureView *)RUNTIME_CLASS(CPictureView)->CreateObject();
//在目标位置动态创建视图
if (NULL == m_picView)
{
return FALSE;
}
m_picView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, RectTargetCtrl, this, TargetCtrlID, NULL);
// 方法二:
UINT TargetCtrlID = IDC_STATIC_VIEW;
CWnd *pWnd = this->GetDlgItem(TargetCtrlID);
CRect RectTargetCtrl;
pWnd->GetWindowRect(RectTargetCtrl);
pWnd->DestroyWindow();
this->ScreenToClient(RectTargetCtrl);
CCreateContext context;
context.m_pCurrentDoc = NULL;//不要文档为空
context.m_pCurrentFrame = (CFrameWnd *)this;//设置父窗体指针,将对话框指针强制转换
context.m_pLastView = NULL;//前一个视图为空
context.m_pNewDocTemplate = NULL;//文档模板为空
context.m_pNewViewClass = RUNTIME_CLASS(CPictureView);
CFrameWnd* pfWnd=(CFrameWnd *)this; // 将对话框强制转换为CFrameWnd
m_picView = (CPictureView *)pfWnd->CreateView(&context);
m_picView->MoveWindow(RectTargetCtrl);
4.有了一个新的问题,对话框中生成后如果点击视图区域,就会出现内存错误,当忽略后如果想要退出系统就退不出去了。
通过寻找相关信息发现,发现当没有给CView使用DYNAMIC_CREATE宏时,MFC不调用OnMouseActivate所以在这里需要进行处理。于是在创建的视图类中间手工添加消息映射
头文件中添加:afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT msg);
源文件中添加:
ON_MESSAGE(WM_MOUSEACTIVATE, OnMouseActivate) ,并实现OnMouseActivate消息
int CTestView::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT msg)
{
return CWnd::OnMouseActivate(pDesktopWnd, nHitTest, msg);
}
运行程序,OK,成功!
5.至于为什么要这样做,有待思考...