Get cursor position with respect to the control - C#

前端 未结 11 2339
迷失自我
迷失自我 2020-12-05 23:23

I want to get the mouse position with respect to the control in which mouse pointer is present. That means when I place the cursor to the starting point (Top-Left corner) of

相关标签:
11条回答
  • 2020-12-05 23:46

    Snippet code as following:

    private void Control_MouseMove(object sender, MouseEventArgs e)
    {
        var btn = sender as Button;
        var point = e.Location;
        point.X += btn.Location.X;
        point.Y += btn.Location.Y;
    
        Control findTarget = btn.Parent.GetChildAtPoint(point, GetChildAtPointSkip.Invisible) as Button;
        if (findTarget != null)
        {
            // TO DO
        }
    }
    

    Where the button is one of many buttons in a hosting panel.

    0 讨论(0)
  • 2020-12-05 23:48
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        Text = panel1.PointToClient(Cursor.Position).ToString();    
    } 
    
    0 讨论(0)
  • 2020-12-05 23:50

    One can use following methods for getting the relative from absolute and absolute from relative coordinates:

    Point Control.PointToClient(Point point);
    
    Point Control.PointToScreen(Point point);
    
    0 讨论(0)
  • 2020-12-05 23:51

    Simply subtract from the cursor position the Left and Top coordinates of the control:

    this.Text = Convert.ToString(
        Cursor.Position.X - this.Left + ":" +
        Cursor.Position.Y - this.Top);
    
    0 讨论(0)
  • 2020-12-05 23:56

    Use Control.PointToClient to convert a point from screen-relative coords to control-relative coords. If you need to go the other way, use PointToScreen.

    0 讨论(0)
提交回复
热议问题