1.首先添加成员变量:
bool bIsDrawing; //画线标志
int DrawLinewidth; //线条宽度
CPoint ptDrawOrigin; //当前线段的起始点
HCURSOR Hcross; //光标形状
2. 添加鼠标消息响应函数:
OnLButtonDown(UINT nFlags, CPoint point);
OnMouseMove(UINT nFlags, CPoint point);
OnLButtonUp(UINT nFlags, CPoint point);
3.在OnLButtonDown(UINT nFlags, CPoint point);中添加下面代码:
SetCapture();
::SetCursor(Hcross);
ptDrawOrigin = point;
bIsDrawing = true;
4.在OnMouseMove(UINT nFlags, CPoint point);中添加下面代码:
if(bIsDrawing)
{
CPen pen(PS_DOT, DrawLinewidth, RGB(255, 0, 0));//构造画笔对象
CClientDC dc(this);
CPen *pOldPen = dc.SelectObject(&pen);//将画笔选入DC
dc.MoveTo(ptDrawOrigin);
dc.LineTo(point);
dc.SelectObject(pOldPen);//恢复先前的画笔
ptDrawOrigin = point;
}
5.在OnLButtonUp(UINT nFlags, CPoint point);中添加下面代码:
if(bIsDrawing)
{
bIsDrawing=false;
ReleaseCapture();
}
6.在OnInitDialog()中添加初始化代码:
bIsDrawing =false; //初始化绘图状态
DrawLinewidth = 10; //设置线条宽度
Hcross = LoadCursor(NULL, IDC_CROSS); //十字型光标
// Hcross = LoadCursor(NULL, IDC_ARROW); //正常箭头光标
::SetCursor(Hcross);
源码下载: