Maison  >  Questions et réponses  >  le corps du texte

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

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

迷茫迷茫2714 Il y a quelques jours543

répondre à tous(1)je répondrai

  • 迷茫

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

    时间仓促,先回答一半。
    获取鼠标指针在窗口内的坐标很简单,我这里用了WM_MOUSEMOVE消息响应函数。先看一下我的示例窗口组成:

    下面的标签用来输出结果。然后直接上代码看:

    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);
    }

    以上就是关于鼠标指针的问题。
    至于在static上画图,因为是先响应OnPaint,所以不能在OnPaint里在static上绘图。可以用定时器绕过这个问题,在Timer的事件响应函数中完成在static上的绘图。或者从CStatic类派生自己的static类,覆盖

    virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);

    这个虚函数。

    répondre
    0
  • Annulerrépondre