This blog will be helpful for those who want to draw a rectangle using mouse dragging feature and show a re-sizing handler and also want to move a rectangle from one position to another.
Step 1
Open the .h header file of subclass of CView in editor.
Eg: In this example , using CDrawViewView.h header file which is subclass of CView.
Step 2
Declare a protected variable in .h file.
CRectTracker m_RectTracker; // Rect Tracker
CArray<CRect, CRect&> m_RectArray; // Contains reference of Rect
Step 3
Declare a protected method in .h file.
- bool LMouseButtonDown(CPoint point);
- afx_msg void OnLButtonDown(UINT flags, CPoint point);
- afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
- afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
Step 4
Open .m file such as CDrawViewView.m in editor and modify begin message map and declare message block.
- BEGIN_MESSAGE_MAP(CDrawViewView, CView)
- ON_WM_LBUTTONDOWN()
- ON_WM_SETCURSOR()
- END_MESSAGE_MAP()
Step 5
And placed following code in .m file.
- CDrawViewView::CDrawViewView()
- {
- m_RectTracker.m_rect.SetRect(-1,-1,-1,-1);
- m_RectTracker.m_nStyle = CRectTracker::resizeOutside|CRectTracker::dottedLine;
- }
-
-
- bool CDrawViewView::LMouseButtonDown(CPoint point)
- {
- bool status = false;
- int rectCount = m_RectArray.GetCount();
-
- if (rectCount <= 0)
- return status;
- for (int i = 0; i < rectCount; ++i)
- {
- CRect rect = m_RectArray[i];
- if (rect.PtInRect(point))
- {
- m_RectTracker.m_rect = rect;
- m_RectArray.RemoveAt(i);
- status = true;
- break;
- }
- }
- return status;
- }
-
-
- void CDrawViewView::OnLButtonDown(UINT nFlags, CPoint point)
- {
- if (!LMouseButtonDown(point))
- {
-
- if (m_RectTracker.TrackRubberBand(this, point, true))
- {
- CRect rect = new CRect(m_RectTracker.m_rect);
- m_RectArray.Add(rect);
- }
- }
- else
- {
- m_RectTracker.Track(this, point, true);
- CRect rect = new CRect(m_RectTracker.m_rect);
- m_RectArray.Add(rect);
- }
-
- Invalidate();
- CView::OnLButtonDown(nFlags, point);
-
-
- void CDrawViewView::OnDraw(CDC* pDC)
- {
- CDrawViewDoc* pDoc = GetDocument();
- ASSERT_VALID(pDoc);
- if (!pDoc)
- return;
-
-
- int rectCount = m_RectArray.GetCount();
- if (rectCount > 0)
- {
- for (int i = 0; i < rectCount; ++i)
- {
- CRect currentRect = m_RectArray[i];
- pDC->Rectangle(currentRect);
- }
- m_RectTracker.Draw(pDC);
- }
- }