昨天写一个简单的画图程序,遇到一个奇怪的问题,目的是想点鼠标左键,画个以此点为中心画个椭圆,最初的代码如下:
void
CE02View::OnLButtonDown(UINT nFlags, CPoint point)
{
CPaintDC dc(
this
);
OnPrepareDC(
&
dc);
if
(
this
->
m_nColor
==
GRAY_BRUSH)
{
this
->
m_nColor
=
WHITE_BRUSH;
}
else
{
this
->
m_nColor
=
GRAY_BRUSH;
}
this
->
m_rectEllipse.left
=
point.x
/
2
;
this
->
m_rectEllipse.right
=
point.x
+
point.x
/
2
;
this
->
m_rectEllipse.top
=
point.y
+
point.y
/
2
;
this
->
m_rectEllipse.bottom
=
point.y
/
2
;
this
->
OnDraw(
&
dc);
CView::OnLButtonDown(nFlags, point);
}
void
CE02View::OnDraw(CDC
*
pDC)
{
CE02Doc
*
pDoc
=
GetDocument();
ASSERT_VALID(pDoc);
pDC
->
SelectStockObject(
this
->
m_nColor);
pDC
->
Ellipse(
this
->
m_rectEllipse);
}
并且也考虑了第一次运行时会发出WM_PAINT事件,而在OnPaint方法里会去调用OnDraw(),所以我把OnPaint重写了,让其不调用OnDraw,这样第一次运行就不会去画了。
void
CE02View::OnPaint()
{
CPaintDC dc(
this
);
//
device context for painting
}
可尽管这样,点击鼠标左键还是无法画出东西来,问了下师兄,他也不熟悉VC,弄了一会儿也无功而返,今天想了下可能是DC有问题,换了个CClientDC,唉,好了,真是怪了,用CPaintDC我是想模仿这OnPaint()的代码来写,按道理说应该可以的,可为什么在OnLButtonDown里就不行呢?最后可以运行的代码如下:
void
CE02View::OnLButtonDown(UINT nFlags, CPoint point)
{
CClientDC dc(
this
);
OnPrepareDC(
&
dc);
if
(
this
->
m_nColor
==
GRAY_BRUSH)
{
this
->
m_nColor
=
WHITE_BRUSH;
}
else
{
this
->
m_nColor
=
GRAY_BRUSH;
}
this
->
m_rectEllipse.left
=
point.x
/
2
;
this
->
m_rectEllipse.right
=
point.x
+
point.x
/
2
;
this
->
m_rectEllipse.top
=
point.y
+
point.y
/
2
;
this
->
m_rectEllipse.bottom
=
point.y
/
2
;
this
->
OnDraw(
&
dc);
CView::OnLButtonDown(nFlags, point);
}
这样看来,CPaintDC是专门用来在响应WM_PAINT消息时使用的,其他消息处理程序中不能使用