Home  >  Q&A  >  body text

c++ - 请问在MFC对话框中,如何获取鼠标相对于对话框中CStatic控件左上角的坐标?

在我的对话框中有一个CStatic控件,我现在希望在CStatic空间上进行绘图,并且同时能够获取鼠标相对于CStatic控件上左上角的坐标并将坐标保存下来,请问应该如何去做?
非常感谢。

迷茫迷茫2764 days ago582

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 15:30:54

    Time is short, so I’ll answer half of it first.
    Getting the coordinates of the mouse pointer in the window is very simple. I used the WM_MOUSEMOVE message response function here. Let’s take a look at my sample window composition first:

    The following tags are used to output the results. Then go directly to the code to see:

    void CStaticDrawDlg::OnMouseMove(UINT nFlags, CPoint point)
    {
        // TODO: Add your message handler code here and/or call default
        TCHAR buffer[255];        //用来保存结果的字符串
        memset(buffer, 0, 255);
    
        CRect staticRect;        //用来保存static控件的大小
        (GetDlgItem(IDC_STATIC_DRAW))->GetWindowRect(&staticRect);    //获取static大小
        ScreenToClient(&staticRect);        //把相对屏幕的坐标转换成相对当前窗口客户区的大小
    
        CPoint insidePoint;                //用来保存鼠标指针相对static控件坐标
        insidePoint.x = point.x - staticRect.left;    //当前相对客户区的x坐标减去static的左侧位置即为鼠标指针相对static的坐标
        insidePoint.y = point.y - staticRect.top;    //同上
    
        //下面把结果显示到另一个static控件上
        wsprintf(buffer, 
            _T("当前鼠标指针相对于窗口的x坐标为%d,y坐标为%d\n相对于用来绘图的static的x坐标为%d,y坐标为%d"), 
            point.x, point.y, insidePoint.x, insidePoint.y);
        (GetDlgItem(IDC_STATIC_OUTPUT))->SetWindowText(buffer);
        CDialogEx::OnMouseMove(nFlags, point);
    }

    The above is about the mouse pointer issue.
    As for drawing on static, because it responds to OnPaint first, you cannot draw on static in OnPaint. You can use a timer to bypass this problem and complete static drawing in the Timer's event response function. Or derive your own static class from CStatic class and override

    virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);

    This virtual function.

    reply
    0
  • Cancelreply