新建了一个当文档的vc工程,在OnDraw中添加了如下代码。
void CMyView::OnDraw(CDC* pDC)
{
CMyDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
pDC->TextOut(100,100,"OnDraw");
}
执行,结果在(100,100)处出现了"OnDraw"字样。
在vc安装目录/vc98/MFC/SRC,找到viewcore.cpp,按下"ctrl+f",输入OnPaint,调出如下代码:
void CView::OnPaint()
{
// standard paint routine
CPaintDC dc(this);
OnPrepareDC(&dc);
OnDraw(&dc);
}
OnPaint是CWnd的成员函数,而OnDraw则是CView的虚函数。由于我没有重定义OnPaint函数,所以默认执行CView::OnPaint()函数,当执行到OnDraw(&dc);时,由于它是虚函数,所以实际执行的是
CMyView::OnDraw函数,所以出现了如上结果。
为CMyView添加WN_PAINT消息,OnPaint函数如下:
void CMyView::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CView::OnPaint() for painting messages
}
执行,没有出现任何反应,原因是void CMyView重写了OnPaint函数,而void CMyView::OnPaint() 函数里边没有任何代码,所以没有反应。修改void CMyView::OnPaint() 如下:
void CMyView::OnPaint()
{
CPaintDC dc(this); // device context for painting
OnDraw(&dc);
}
执行,结果在(100,100)处出现了"OnDraw"字样。
注意:
a.在处理WM_PAINT消息时,只能用BeginPaint和EndPaint.
b.CPaintDC对象在构造时调用CWnd::BeginPaint,在析构的时候调用CWnd::EndPaint,刚好符合a.
c.在客户区绘图时,要用GetDC和ReleaseDC.
d.CClientDC对象在构造时调用GetDC,在析构时调用ReleaseDC,刚好符合c.