Get cursor position in a panel with scroll bars
I've created a simple program (for now) that has a large panel as the "WorkArea" of the program. I draw a grid on it, have some functions that snap my cursor to the nearest grid point, etc. I have a status bar at the bottom of the window that displays my current position in the panel. However, no matter where I scrolled (let's say the vertical bar is 10% relative to the top and the horizontal bar is 25%), it displays my cursor position relative to the actual window.
I have an 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 expect, giving cursor points, drawing it to the desired location, etc. However, if I scroll, I still get the same readings. I could scroll halfway along the vertical and horizontal scrollbars, place the cursor in the top left corner, and read 0,0 when it should be something like 5000500 (on a 10k by 10k panel).
How can you get the absolute position within the panel in relation to its scrollbars?
source to share
You need to offset the location with 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 AutoScrollPosition values are negative ..:
The resulting X and Y coordinate values ββare negative if the control bounces from its original position (0,0). When you set this property, you should 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 set x and y to 100 the scroll appears to move to the left 100px because you are setting 100px from the starting position. In the first case, AutoScrollPosition returns {-200, 0}; in the second case, it returns {-100,0}.
source to share
WinForms:
The Control.PointToClient method converts the position of the mouse 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);
source to share