MFC中在view窗口画线的四种方法
第一步:
得在CView窗口类里定义一个全局变量来记录鼠标点击时的光标位置,代码:CPoint m_beginpt;
第二步:
在CView窗口类里添加鼠标左按钮点击消息响应函数,添加后编辑代码,具体如下:
void CDrawlineView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default m_beginpt=point; CView::OnLButtonDown(nFlags, point); } |
第三步:
在CView窗口类里添加鼠标左按钮弹起消息响应函数,添加后编辑代码,这里有四种方法。
方法一:通过调用platform SDK里面的函数来实现,而没有使用MFC类库的函数。代码如下:
void CDrawlineView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default HDC hdc; hdc=::GetDC(m_hWnd); MoveToEx(hdc,m_beginpt.x,m_beginpt.y,NULL); LineTo(hdc,point.x,point.y); ::ReleaseDC(m_hWnd,hdc); CView::OnLButtonUp(nFlags, point); } |
方法二:通过使用MFC类库的CDC类来实现。代码如下:
void CDrawlineView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CDC * cdc=CWnd::GetDC(); cdc->MoveTo(m_beginpt.x,m_beginpt.y); cdc->LineTo(point.x,point.y); cdc->DeleteDC(); CView::OnLButtonUp(nFlags, point); } |
注意:因为是窗口获得DC,所以GetDC是窗口下面的成员变量,而不是CDC类的成员变量。
方法三:通过调用MFC类库里的CClientDC类来实现,代码如下:
void CDrawlineView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CClientDC cdc(this); cdc.MoveTo(m_beginpt.x,m_beginpt.y); cdc.LineTo(point.x,point.y); CView::OnLButtonUp(nFlags, point); } |
注意:CClientDC可以自动调用GetDC函数和ReleaseDC函数,而且可以在mainframe框架的客户区划线。
方法四:通过调用MFC类库里的CWindowDC类来实现。
void CDrawlineView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CWindowDC cwnddc(this); cwnddc.MoveTo(m_beginpt.x,m_beginpt.y); cwnddc.LineTo(point.x,point.y); // cwnddc.DeleteDC(); CView::OnLButtonUp(nFlags, point); } |
注意:CWindowDC可以自己调用GetWindowDC函数。