Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c# - Get Position of cursor on panel with scrollbars

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...