vc中圆形跟随者鼠标移动

vc中圆形跟随者鼠标移动_第1张图片

1.全局变量:

const CSize m_sizeEllipse;

CPoint m_pointTopLeft; 

CSize  m_sizeOffset;  
BOOL   m_bCaptured;

初始化:

m_sizeEllipse(100, -100),
m_pointTopLeft(0, 0),
m_sizeOffset(0, 0)

2,

OnDraw(CDC* pDC)
{

.............................省略

 //创建红色画刷
 CBrush brushHatch(HS_DIAGCROSS, RGB(168, 168, 168));
    CPoint point(0, 0);              
  //转换逻辑坐标到设备坐标
    pDC->LPtoDP(&point);                
    pDC->SetBrushOrg(point);            
    CBrush* pOldBrush = pDC->SelectObject(&brushHatch);
 //画红色圆圈
    pDC->Ellipse(CRect(m_pointTopLeft, m_sizeEllipse));
 pDC->SelectObject(pOldBrush);

}

3.鼠标滑动事件

void Ctest1View::OnMouseMove(UINT nFlags, CPoint point)
{
 if (m_bCaptured) {
  //如果有图形被选中,并且鼠标被捕捉则更新图形位置
        CClientDC dc(this);
        OnPrepareDC(&dc);
        CRect rectOld(m_pointTopLeft, m_sizeEllipse);
        dc.LPtoDP(rectOld);
  //擦除老位置的图形
        InvalidateRect(rectOld, TRUE);
        m_pointTopLeft = point - m_sizeOffset;
        dc.DPtoLP(&m_pointTopLeft);
  //在新位置画图形
        CRect rectNew(m_pointTopLeft, m_sizeEllipse);
        dc.LPtoDP(rectNew);
        InvalidateRect(rectNew, TRUE);
    }

 CView::OnMouseMove(nFlags, point);
}

4.按下鼠标左键

void Ctest1View::OnLButtonDown(UINT nFlags, CPoint point)
{
    CRect rectEllipse(m_pointTopLeft, m_sizeEllipse);
    CRgn  circle;

    CClientDC dc(this);
    OnPrepareDC(&dc);
    dc.LPtoDP(rectEllipse);
    circle.CreateEllipticRgnIndirect(rectEllipse);
    if (circle.PtInRegion(point))

   {
        //捕捉鼠标
        SetCapture();
        m_bCaptured = TRUE;
        CPoint pointTopLeft(m_pointTopLeft);
        dc.LPtoDP(&pointTopLeft);
        m_sizeOffset = point - pointTopLeft;

        //设置光标形状为十字状
        ::SetCursor(::LoadCursor(NULL, IDC_CROSS));
    }

CView::OnLButtonDown(nFlags, point);
}

5.

//释放左键触发事件

void Ctest1View::OnLButtonUp(UINT nFlags, CPoint point)
{
 // // TODO: Add your message handler code here and/or call default
 if (m_bCaptured) {
  //释放鼠标捕捉
        ::ReleaseCapture();
        m_bCaptured = FALSE;
  }

 CView::OnLButtonUp(nFlags, point);
}

 

你可能感兴趣的:(VC)