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.
  1. bool LMouseButtonDown(CPoint point); // Method called from left mouse buton down event.
  2. afx_msg void OnLButtonDown(UINT flags, CPoint point);
  3. afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
  4. 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.
  1. BEGIN_MESSAGE_MAP(CDrawViewView, CView)
  2. ON_WM_LBUTTONDOWN()
  3. ON_WM_SETCURSOR()
  4. END_MESSAGE_MAP()
Step 5

And placed following code in .m file.
  1. CDrawViewView::CDrawViewView()
  2. {
  3. m_RectTracker.m_rect.SetRect(-1,-1,-1,-1);
  4. m_RectTracker.m_nStyle = CRectTracker::resizeOutside|CRectTracker::dottedLine;
  5. }
  6. /* Method invoked to check whether user selected rectangle or not */
  7. bool CDrawViewView::LMouseButtonDown(CPoint point)
  8. {
  9. bool status = false;
  10. int rectCount = m_RectArray.GetCount();
  11. if (rectCount <= 0)
  12. return status;
  13. for (int i = 0; i < rectCount; ++i)
  14. {
  15. CRect rect = m_RectArray[i];
  16. if (rect.PtInRect(point))
  17. {
  18. m_RectTracker.m_rect = rect;
  19. m_RectArray.RemoveAt(i);
  20. status = true;
  21. break;
  22. }
  23. }
  24. return status;
  25. }
  26. void CDrawViewView::OnLButtonDown(UINT nFlags, CPoint point)
  27. {
  28. if (!LMouseButtonDown(point))
  29. {
  30. if (m_RectTracker.TrackRubberBand(this, point, true))
  31. {
  32. CRect rect = new CRect(m_RectTracker.m_rect);
  33. m_RectArray.Add(rect);
  34. }
  35. }
  36. else
  37. {
  38. m_RectTracker.Track(this, point, true);
  39. CRect rect = new CRect(m_RectTracker.m_rect);
  40. m_RectArray.Add(rect);
  41. }
  42. Invalidate();
  43. CView::OnLButtonDown(nFlags, point);
  44. void CDrawViewView::OnDraw(CDC* pDC)
  45. {
  46. CDrawViewDoc* pDoc = GetDocument();
  47. ASSERT_VALID(pDoc);
  48. if (!pDoc)
  49. return;
  50. int rectCount = m_RectArray.GetCount();
  51. if (rectCount > 0)
  52. {
  53. for (int i = 0; i < rectCount; ++i)
  54. {
  55. CRect currentRect = m_RectArray[i];
  56. pDC->Rectangle(currentRect);
  57. }
  58. m_RectTracker.Draw(pDC);
  59. }
  60. }