Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 closest point on the grid etc. I have a status bar on the bottom of the window which displays my current position on the panel. However, regardless of where I've scrolled to (let's say vertical bar is at 10% relative to top and horizontal is 25%) it displays my cursor position with regards to the actual window.

I have a OnMouseMove event that handles this:

private void WorkArea_MouseMove(object sender, MouseEventArgs e)
{
    GridCursor = grid.GetSnapToPosition(new Point(e.X, e.Y));
    toolStripStatusLabel1.Text = grid.GetSnapToPosition(new Point(e.X, e.Y)).ToString();
    Refresh();
}

It works as I'd expect giving the points of the cursor, drawing it to the correct place, and so on. However, if I scroll out, I still get the same readings. I could be scrolled out half way on the vertical and horizontal scrollbars, put my cursor in the upper left-hand corner, and read a 0,0, when it should be something more like 5000,5000 (on a panel 10k by 10k).

How can one go about getting the absolute position within a panel with respect to its scrollbars?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

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}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...