c# - 使用滚动条获取光标在面板上的位置

标签 c# winforms scroll

我已经构建了一个简单的程序(到目前为止),它有一个大面板作为程序的“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/

相关文章:

c# - ASP.NET machinekey 在代码中设置键

c# - 将 Json 字符串反序列化为多个输出

winforms - Windows 窗体查找所有事件的窗体实例类型

c# - 如何在c#中绘制一个圆角矩形

angular - 在 Angular 中向下滚动时如何使组件消失?

javascript - 如何在 javascript/jquery 中单击文本时滚动到底部?

c# - 如何为 JQuery 插件创建静态方法

c# - 哪些集合具有 Length 或 Count 属性的 Thumbrule - C#

winforms - 无法在 Windows 窗体上拖放 Telerik 组件

css - 水平滚 Action 为自动 flex 元素(或一个)的 <pre> 标签