BeginPaint,获得一个Device Context(DC),然后在这个DC上作画。这个DC代表屏幕设备。在MFC里头,一旦WM_PAINT消息发生,表示画面需要重绘,此框架会自动调用OnDraw 函数。
通过查看MFC源码(位于”%programfiles%\Microsoft Visual Studio 9.0\VC\atlmfc\src”),可以得知函数OnPaint、OnPrint和OnDraw间的关系。
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)只是为了实现各种不同设备上绘图的一致性。