绘图基础--橡皮筋画线
绘图基础--橡皮筋画线
橡皮筋画线:用户点击鼠标左键定下一个起点,然后把鼠标拖到目标终点,这时程序就会在起始点间画线。

// rubber.cpp#include <afxwin.h>// Define the application classclass CApp : public CWinApp{public:virtual BOOL InitInstance();};CApp App; // Define the window classclass CWindow : public CFrameWnd{ HCURSOR cross;HCURSOR arrow;CPoint start, old;BOOL started;public:CWindow(); afx_msg void OnMouseMove(UINT,CPoint);afx_msg void OnLButtonDown(UINT, CPoint);afx_msg void OnLButtonUp(UINT, CPoint);DECLARE_MESSAGE_MAP()};// The window constructorCWindow::CWindow(){ // Load two cursorscross = AfxGetApp()->LoadStandardCursor(IDC_CROSS);arrow = AfxGetApp()->LoadStandardCursor(IDC_ARROW);started=FALSE;// Create a custom window classconst char* pszWndClass = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW, NULL,(HBRUSH)(COLOR_WINDOW+1), NULL);// Create the windowCreate(pszWndClass, "Drawing Tests", WS_OVERLAPPEDWINDOW,CRect(0,0,250,250)); }// The message mapBEGIN_MESSAGE_MAP( CWindow, CFrameWnd )ON_WM_MOUSEMOVE()ON_WM_LBUTTONDOWN()ON_WM_LBUTTONUP()END_MESSAGE_MAP()// Start a new line when the user clicks// the mouse button downvoid CWindow::OnLButtonDown(UINT flag,CPoint mousePos){started = TRUE;::SetCursor(cross);// save the starting position of the linestart = old = mousePos;CClientDC dc(this);dc.SetROP2(R2_NOT);dc.MoveTo(start);dc.LineTo(old);}// Complete the line when the user releases// the mouse buttonvoid CWindow::OnLButtonUp(UINT flag,CPoint mousePos){if (started){started = FALSE;::SetCursor(arrow);CClientDC dc(this);dc.MoveTo(start);dc.LineTo(old);}}// Handle draggingvoid CWindow::OnMouseMove(UINT flag,CPoint mousePos){// If the mouse button is down and there// is a line in progress, rubber bandif ((flag == MK_LBUTTON) && started){::SetCursor(cross);CClientDC dc(this);dc.SetROP2(R2_NOT);// Undraw the old linedc.MoveTo(start);dc.LineTo(old);// Draw the new linedc.MoveTo(start);dc.LineTo(mousePos);old=mousePos;}else::SetCursor(arrow);}// Init the applicationBOOL CApp::InitInstance(){m_pMainWnd = new CWindow();m_pMainWnd->ShowWindow(m_nCmdShow);m_pMainWnd->UpdateWindow();return TRUE;}