• 2008年05月13日

    函数OnPaint、OnPrint和OnDraw间的区别联系

    分类:

    在传统的C/SDK 程序中,当窗口函数收到WM_PAINT消息,程序员就调用

    BeginPaint,获得一个Device ContextDC),然后在这个DC上作画。这个DC代表屏幕设备。在MFC里头,一旦WM_PAINT消息发生,表示画面需要重绘,此框架会自动调用OnDraw 函数。

     

    通过查看MFC源码(位于”%programfiles%\Microsoft Visual Studio 9.0\VC\atlmfc\src”),可以得知函数OnPaintOnPrintOnDraw间的关系。

    1.     函数OnPaint()定义在Afxwin.h

    class CWnd : public CCmdTarget

    {

          ...

          afx_msg void OnPaint();

          ...

    }

     

    class AFX_NOVTABLE CView : public CWnd

    {   

          ...

          afx_msg void OnPaint();

          ...

    }

     

    其中CWnd的实现在wincore.cpp

    void CWnd::OnPaint()

    {

       if (m_pCtrlCont != NULL)

       {

            // Paint windowless controls

            CPaintDC dc(this);

            m_pCtrlCont->OnPaint(&dc);

       }

     

       Default();

    }

    /* m_pCtrlCont定义在afxwin.h

    COleControlContainer* m_pCtrlCont;  // for containing OLE controls

    */

     

    CView的实现在Viewcore.cpp

    void CView::OnPaint()

    {

          // standard paint routine

          CPaintDC dc(this);

          OnPrepareDC(&dc);

          OnDraw(&dc);

    }

     

    2.     虚函数OnPrint()作为CView类的成员函数定义在afxwin.h

    virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);

    实现在Viewcore.cpp

    void CView::OnPrint(CDC* pDC, CPrintInfo*)

    {

          ASSERT_VALID(pDC);

     

          // Override and set printing variables based on page number

          OnDraw(pDC);                    // Call Draw

    }

     

    3.     OnDraw CView类中最重要的成员函数,负责将Document的数据显示出来,所有的绘图动作都应该放在其中。它被定义为纯虚函数在afxwin.h中,可以被重写(Override)

    virtual void OnDraw(CDC* pDC) = 0;

    实现在Viewcore.cpp

    void CView::OnDraw(CDC*)

    {

    }

     

    见图:

     

     

    综上,标准消息WM_PAINT总跟OnPaint函数相关,命令消息(Command Message,以WM_COMMAND表示,来自菜单或工具栏)即事件ID_FILE_PRINT总跟OnPrint函数相关,而函数OnDraw不属于消息映射(Message Mapping)只是为了实现各种不同设备上绘图的一致性。


    历史上的今天:

    Windows消息 2008年05月13日

    随机文章:

    IDR_MAINFRAME资源 2008年09月06日
    指针常量和常量指针 2008年09月05日
    图形的保存和重绘 2008年08月01日
    开源富按钮类 2008年07月23日

    收藏到:Del.icio.us




    评论

  • 請問 :
    OnPrint 屬於 CView 類別 , 若要在 Dialog 專案中想將資料由印表機輸出 , 該如何實現
    阿里回复莊明元说:
    可以创建临时的CFrameWnd和CView对象,见http://www.codeproject.com/KB/printing/print_preview.aspx.
    2008-11-04 19:21:04