#ifndef _DRAW_H
#define _DRAW_H
#include <afxwin.h>
class CMyApp:public CWinApp
{
public:
BOOL InitInstance();
};
class CMainWnd:public CFrameWnd
{
public:
CMainWnd();
protected:
DECLARE_MESSAGE_MAP();
afx_msg void OnLButtonDown(UINT nflags,CPoint point);
afx_msg void OnLButtonUp(UINT nflags,CPoint point);
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags,CPoint point);
void InvertLine(CClientDC*,CPoint,CPoint);
bool m_istrack;
CPoint m_ptfrom;
CPoint m_ptto;
};
#endif
#include "draw.h"
CMyApp app;
BOOL CMyApp::InitInstance()
{
m_pMainWnd=new CMainWnd;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return true;
}
BEGIN_MESSAGE_MAP(CMainWnd,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_PAINT()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
CMainWnd::CMainWnd()
{
Create(NULL,"橡皮筋程序");
m_ptfrom=m_ptto=CPoint(0,0);
m_istrack=false;
}
void CMainWnd::InvertLine(CClientDC *dc,CPoint From,CPoint To)
{
int oldmode=dc->SetROP2(R2_NOT); //将绘图模式设置为正反模式,即为反转当前的像素点来绘图
dc->MoveTo(From);
dc->LineTo(To);
dc->SetROP2(oldmode);
}
void CMainWnd::OnPaint()
{
CPaintDC dc(this);
dc.TextOut(0,0,"是不是干活干多了认识就提升了,代码写多了品质就提升了");
}
void CMainWnd::OnLButtonDown(UINT nFlags,CPoint point)
{
SetCapture();
m_ptfrom=point;
m_istrack=true;
}
void CMainWnd::OnMouseMove(UINT nFlags,CPoint point)
{
if(m_istrack){
m_ptto=point;
CClientDC dc(this);
InvertLine(&dc,m_ptfrom,m_ptto);
InvertLine(&dc,m_ptfrom,point);
}
}
void CMainWnd::OnLButtonUp(UINT nFlags,CPoint point)
{
if(m_istrack){
if(GetCapture()==this){ //是否已设置了SetCapture
ReleaseCapture();
m_ptto=point;
CClientDC dc(this);
CPen Pen(PS_SOLID,10,RGB(255,0,0)); //选择新的画笔时将旧的画笔选出
CPen* poldPen=dc.SelectObject(&Pen);
InvertLine(&dc,m_ptfrom,m_ptto);
dc.SelectObject(poldPen);
m_istrack=false;
}
}
}
在橡皮筋程序中,在OnLButtonDown使用SetCapture();在OnLButtonUp使用ReleaseCapture();