本例子的功能是 在 view 上画一个椭圆。通过鼠标拖动自动画,每次画椭圆之前都删除以前画的椭圆 。

一 . 首先建立一个单文档程序,名字为:DrawEllipse

二 . 然后在CDrawEllipseView 类中添加成员变量:

public:
Rect rect;
BOOL m_flag;

三 . 在CDrawEllipseView 类构造器中添加初始化代码:

CDrawEllipseView::CDrawEllipseView()
{
    // TODO: add construction code here
     CPoint cp(0,0);
     rect=new CRect(cp,cp);
     m_flag=false;
}

四 . 添加 消息映射代码

ON_WM_MOUSEMOVE:
void CDrawEllipseView::OnMouseMove(UINT nFlags, CPoint point) 
{
 // TODO: Add your message handler code here and/or call default
 if(m_flag)
 {
  rect.right=point.x;
  rect.bottom=point.y;
  Invalidate();
 }
 CView::OnMouseMove(nFlags, point);
} ON_WM_LBUTTONDOWN:
void CDrawEllipseView::OnLButtonDown(UINT nFlags, CPoint point) 
{
 // TODO: Add your message handler code here and/or call default
 
 CView::OnLButtonDown(nFlags, point);
 m_flag=true;
 rect.left=point.x;
 rect.top=point.y;
} ON_WM_LBUTTONUP:
void CDrawEllipseView::OnLButtonUp(UINT nFlags, CPoint point) 
{
 // TODO: Add your message handler code here and/or call default
 m_flag=false;
 CView::OnLButtonUp(nFlags, point);
}

五 . 重写OnDraw

void CDrawEllipseView::OnDraw(CDC* pDC)
{
 CDrawEllipseDoc* pDoc = GetDocument();
 ASSERT_VALID(pDoc);
    if(rect.Width()>10 && rect.Height()>10)
 {
  CPen penA(PS_DOT,1,RGB(255,0,0));
  CPen * pOldPen=NULL;
  pOldPen=pDC->SelectObject(&penA);  pDC->SelectStockObject(NULL_BRUSH);
  pDC->Ellipse(rect);
  pDC->SelectObject(pOldPen);
 } 
 // TODO: add draw code for native data here
}

这个程序就ok了。