1,添加鼠标左键按下Windows Message的响应函数OnLButtonDown;添加鼠标左键弹起响应函数OnLButtonUp。右键view类>>属性,然后在WM消息中选择OnLButtonDown和OnLButtonUp.
2. 在view类中添加成员变量,各个变量的使用原因见注释
3. 在OnLButtonDown函数中 获取/保存 鼠标原点 (鼠标左键按下去时刻的坐标)和写标号m_bDrav = TRUE
4.在OnButtonUp函数中实现画线(打开相应的代码即可)(有关画刷和位图请读者自行理解)
void CxxxxView::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
//
/*使用全局SDK 实现画直线
HDC hdc;
hdc = ::GetDC(m_hWnd);
MoveToEx(hdc, m_ptOrigin.x, m_ptOrigin.y, NULL);
LineTo(hdc, point.x, point.y);
::ReleaseDC(m_hWnd, hdc);
*/
/*使用CDC (MFC)
CDC* pDC = GetDC();
pDC->MoveTo(m_ptOrigin);
pDC->LineTo(point);
ReleaseDC(pDC);
*/
/*使用CClientDC
//CClientDC dc(GetParent());
CClientDC dc(this);
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);//不需要调用release
*/
/*使用CWindowDC
//CWindowDC dc(this);
//CWindowDC dc(GetParent());
CWindowDC dc(GetDesktopWindow());
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);//不需要释放
*/
/*选择画笔颜色粗细
//CPen pen(PS_SOLID,10,RGB(0,255,0));
CPen pen(PS_DOT, 10, RGB(0, 255, 0));
//CPen pen(PS_DASH, 1, RGB(0, 255, 0));
CClientDC dc(this);
CPen *pOldPen = dc.SelectObject(&pen);
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
dc.SelectObject(pOldPen);
*/
//选择画刷
//CBrush brush(RGB(255,0,0));
//CClientDC dc(this);
//dc.FillRect(CRect(m_ptOrigin, point), &brush);
//位图画刷
//CBitmap bitmap;
//bitmap.LoadBitmapW(IDB_BITMAP1);
//CBrush brush(&bitmap);
//CClientDC dc(this);
//dc.FillRect(CRect(m_ptOrigin, point), &brush);
//透明画刷
//CClientDC dc(this);
//CBrush* pBrush = CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));
//CBrush* pOldBrush = dc.SelectObject(pBrush);//dc.SelectObject(&pBrush);
//dc.Rectangle(CRect(m_ptOrigin,point));
//dc.SelectObject(pOldBrush);
m_bDrav = FALSE;
CView::OnLButtonUp(nFlags, point);
}
5.要实现画非直线或者扇形线,需要添加windows对鼠标移动的响应函数OnMouseMove
6.实现方式如代码在函数OnMouseMove中(根据需要选择想用的线和代码)
void CSunXinjiaocheng02View::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
//画随机线
/*
CClientDC dc(this);
CPen pen(PS_SOLID,1,RGB(255,0,0));//选择线的颜色
CPen* pOldPen = dc.SelectObject(&pen);
if (TRUE == m_bDrav)
{
dc.SetROP2(R2_BLACK);//绘画的模式
dc.MoveTo(m_ptOrigin);
//dc.LineTo(point);//画随机线
//m_ptOrigin = point;
//画扇形
dc.LineTo(m_pOld);
//dc.MoveTo(m_ptOrigin);
dc.MoveTo(m_pOld);
dc.LineTo(point);
m_pOld = point;
}
dc.SelectObject(pOldPen);
*/
CView::OnMouseMove(nFlags, point);
}
重点:里面用到了HDC,CDC,CClientDC,WindowsDC ,CPen,CBrush,CBitmap类创建对象并用到了很多相关的成员函数,这些需要读者自行去搜索查看。也可以下载MSDN(2008版本)查看:链接:https://pan.baidu.com/s/1UPpu61qQMQGk4kLjYl5WbQ
提取码:a620