首先我们说下通过鼠标的移动来绘制直线。
这里要捕获到鼠标的两个消息: WM_LBUTTONDOWN, WM_LBUTTONUP。响应WM_LBUTTONDOWN消息记录直线的起始点,响应 WM_LBUTTONUP消息记录直线的终点并绘制直线。
好了,我们看看怎么响应。
void CDrawView::OnLButtonDown(UINT nFlags, CPoint point)
{
//MessageBox("Left Button Clicks DrawView");
m_ptOrigin = point ; //这里先定义了一个内部变量保存直线的起始点
CView::OnLButtonDown(nFlags, point);
}
下面看看响应WM_LBUTTONUP消息记录直线的终点并绘制直线。
//方法一
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
HDC hdc;
hdc = ::GetDC(m_hWnd); //调用全局函数
MoveToEx (hdc,m_ptOrigin.x,m_ptOrigin.y,0);
LineTo(hdc,point.x,point.y);
::ReleaseDC(m_hWnd,hdc);
CView::OnLButtonUp(nFlags, point);
}
//方法二
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
CDC *pDC = GetDC();
pDC->MoveTo(m_ptOrigin);
pDC->LineTo (point);
ReleaseDC(pDC);
}
//方法三
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
CClientDC dc (this) ; //CClientDC对象构造的时候就调用了GetDC,析构的时候调用
ReleaseDC ,只能访问客户区
CClientDC dc(GetParent());
dc.MoveTo (m_ptOrigin);
dc.LineTo(point);
}
//方法四
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
CWindowDC dc (this) ; //CWindowDC可以访问客户区和非客户区
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
}
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
CWindowDC dc(GetDesktopWindow()) ; //现在可以访问桌面
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
}