在CFormView或对话框中动态添加CScrollView、CFormView

本文介绍如何在CFormView和CDialog中动态创建CScrollView,并提供具体实现代码。注意需重写特定成员函数以避免运行时错误。

 本代码可以在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类)

http://www.seeitco.com/doc/Html/Visual%20C++/205707715.html

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值