在CFormView或对话框中动态添加CScrollView、CFormView 收藏本代码可以在CFormView中,根据事先画好的控件位置创建CScrollView 也可以在CDialog中创建CScrollView、CFormView等 注: 若以下代码放在CMainRightView::OnCreate(LPCREATESTRUCT lpCreateStruct)内,则GetDlgItem()函数将调用失败,因为此时控件都还未被创建! void CMainRightView::OnInitialUpdate()
{ CFormView::OnInitialUpdate(); // TODO: Add your specialized code here and/or call the base class //获得目标位置控件 UINT TargetCtrlID = IDC_STATIC_SCROLLVIEW; CWnd *pWnd = this->GetDlgItem(TargetCtrlID); CRect RectTargetCtrl; pWnd->GetWindowRect(RectTargetCtrl); pWnd->DestroyWindow(); this->ScreenToClient(RectTargetCtrl); //在目标位置动态创建CScrollView CEMapView *pEMapView = (CEMapView*)RUNTIME_CLASS(CEMapView)->CreateObject(); pEMapView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, RectTargetCtrl, this, TargetCtrlID); //使用CreateView创建的视图 不能自动调用OnInitialUpdate函数,需要人工调用OnInitialUpdate函数或者发送 WM_INITIALUPDATE消息 pEMapView->OnInitialUpdate(); //SetScrollSizes()必须被调用,否则运行时会出ASSERT错误,当然,也可以在目标View内的OnInitialUpdate()中调用 pEMapView->SetScrollSizes(MM_TEXT, CSize(RectTargetCtrl.Width()-10, RectTargetCtrl.Height()-10)); // 使用CreateView创建的视图不会自动显示并且激活,需要人工操作 pEMapView->ShowWindow(SW_SHOW); } 注:如果需要在CDialog中创建CScrollView、CFormView,则需要overload、override这些View中以下的4个方法,否则会出ASSERT错误 afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message);
afx_msg void OnDestroy(); virtual void PostNcDestroy(); virtual void OnActivateFrame(UINT nState, CFrameWnd* pDeactivateFrame); int CFormViewPrint::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message)
{ // TODO: Add your message handler code here and/or call default return CWnd::OnMouseActivate(pDesktopWnd, nHitTest, message); } void CFormViewPrint::OnDestroy() { CWnd::OnDestroy(); // TODO: Add your message handler code here } void CFormViewPrint::PostNcDestroy() { // TODO: Add your specialized code here and/or call the base class CWnd::PostNcDestroy(); } void CFormViewPrint::OnActivateFrame(UINT nState, CFrameWnd* pDeactivateFrame) { // TODO: Add your specialized code here and/or call the base class CWnd::OnActivateFrame(nState, pDeactivateFrame); } 原因可参考 View和Control的区别(如何在对话框上使用CView类) |
|