#include <afxwin.h>
class CMyApp:public CWinApp{
public:
virtual BOOL InitInstance();
};
class CMainWindow:public CFrameWnd{
protected:
BOOL m_bTracking;
BOOL m_bCaptureEnabled;
CPoint m_ptFrom;
CPoint m_ptTo;
void InvertLine(CDC* pDC,CPoint ptFrom,CPoint ptTo);
public:
CMainWindow();
protected:
afx_msg void OnLButtonDown(UINT nFlags,CPoint point);
afx_msg void OnLButtonUp(UINT nFlags,CPoint point);
afx_msg void OnMouseMove(UINT nFlags,CPoint point);
afx_msg void OnNcLButtonDown(UINT nHitTest,CPoint point);
DECLARE_MESSAGE_MAP()
};
#include"MouseCap.h"
CMyApp myApp;
BOOL CMyApp::InitInstance(){
m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BEGIN_MESSAGE_MAP(CMainWindow,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_NCLBUTTONDOWN()
END_MESSAGE_MAP()
CMainWindow::CMainWindow(){
m_bTracking = FALSE;
m_bCaptureEnabled = TRUE;
CString strWndClass = AfxRegisterWndClass(
0,
AfxGetApp()->LoadStandardCursor(IDC_CROSS),//鼠标样式变为十字
(HBRUSH)(COLOR_WINDOW+1),
AfxGetApp()->LoadStandardIcon(IDI_WINLOGO)
);
Create(strWndClass,_T("Mouse capture demo(Capture Enabled)"));
}
void CMainWindow::OnLButtonDown(UINT nFlags,CPoint point){
m_ptFrom = point;//当鼠标按下时记录鼠标位置
m_ptTo = point;
m_bTracking = TRUE;
if(m_bCaptureEnabled)
SetCapture();
}
void CMainWindow::OnMouseMove(UINT nFlags,CPoint point){
if(m_bTracking){
CClientDC dc(this);
InvertLine(&dc,m_ptFrom,m_ptTo);
InvertLine(&dc,m_ptFrom,point);
m_ptTo = point;
}
}
void CMainWindow::OnLButtonUp(UINT nFlags,CPoint point){
if(m_bTracking){
m_bTracking = false;
if(GetCapture()==this)
::ReleaseCapture();
CClientDC dc(this);
InvertLine(&dc,m_ptFrom,m_ptTo);
CPen pen(PS_SOLID,16,RGB(255,0,0));
dc.SelectObject(&pen);
dc.MoveTo(m_ptFrom);
dc.LineTo(point);
}
}
void CMainWindow::OnNcLButtonDown(UINT nHitTest,CPoint point){
if(nHitTest == HTCAPTION){
m_bCaptureEnabled = m_bCaptureEnabled?FALSE:TRUE;
SetWindowText(m_bCaptureEnabled?
_T("Mouse capture demo(Capture Enabled)"):_T("Mouse capture demo(Capture Disabled)"));
}
CFrameWnd::OnNcLButtonDown(nHitTest,point);
}
void CMainWindow::InvertLine(CDC* pDC,CPoint ptFrom,CPoint ptTo){
int nOldMode=pDC->SetROP2(R2_NOT);
pDC->MoveTo(ptFrom);
pDC->LineTo(ptTo);
pDC->SetROP2(nOldMode);
}
MFC实现鼠标跟踪画直线
PublishedCreated: 2020年9月16日星期三 11:15:38 views(1075)