Get Position of cursor on panel with scrollbars

前端 未结 2 2083
迷失自我
迷失自我 2020-12-21 06:23

I\'ve build a simple program (so far) that has a large panel as the \"WorkArea\" of the program. I draw a grid onto it, have some functionality that snaps my cursor to clos

相关标签:
2条回答
  • 2020-12-21 07:06

    You need to offset the location by the scroll position:

    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
          Point scrolledPoint = new Point( e.X - panel1.AutoScrollPosition.X, 
                                           e.Y - panel1.AutoScrollPosition.Y);
    
          ..
    }
    

    Note that the AutoScrollPosition values are negative..:

    The X and Y coordinate values retrieved are negative if the control has scrolled away from its starting position (0,0). When you set this property, you must always assign positive X and Y values to set the scroll position relative to the starting position. For example, if you have a horizontal scroll bar and you set x and y to 200, you move the scroll 200 pixels to the right; if you then set x and y to 100, the scroll appears to jump the left by 100 pixels, because you are setting it 100 pixels away from the starting position. In the first case, AutoScrollPosition returns {-200, 0}; in the second case, it returns {-100,0}.

    0 讨论(0)
  • 2020-12-21 07:21

    WinForms:

    The method Control.PointToClient lets you convert the mouse position relative to the control itself.

    Point point = grid.PointToClient(new Point(e.X, e.Y))
    

    WPF:

    Using Mouse.GetPosition you can get the position of the mouse relative to a specific control:

    Point position = Mouse.GetPosition(grid);
    
    0 讨论(0)
提交回复
热议问题