我已经构建了一个简单的程序(到目前为止),它有一个大面板作为程序的“WorkArea”。我在上面画了一个网格,有一些功能可以将我的光标捕捉到网格上最近的点等。我在窗口底部有一个状态栏,它显示我在面板上的当前位置。但是,无论我滚动到哪里(假设垂直条相对于顶部为 10%,水平条为 25%),它都会显示我的光标相对于实际窗口的位置。
我有一个处理这个的 OnMouseMove 事件:
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();
}
它的工作方式与我期望的一样,给出光标的点,将其绘制到正确的位置,等等。但是,如果我向外滚动,我仍然会得到相同的读数。我可以在垂直和水平滚动条上滚动到一半,将光标放在左上角,然后读取 0,0,此时它应该更像是 5000,5000(在 10k x 10k 的面板上) .
如何才能获得面板内相对于其滚动条的绝对位置?
最佳答案
您需要通过滚动位置偏移位置:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
Point scrolledPoint = new Point( e.X - panel1.AutoScrollPosition.X,
e.Y - panel1.AutoScrollPosition.Y);
..
}
请注意 AutoScrollPosition值为负..:
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}.
关于c# - 使用滚动条获取光标在面板上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45072620/