我不确定您要做什么,但是如果您要获取图片框内的坐标,图片框类上有一个名为 PointToClient(Point) 的函数,用于计算图片的位置将指定的屏幕点转换为客户端坐标。您可以使用 MouseEventArgs 中的 X 和 Y 坐标来创建 Point 对象以传递给函数。
澄清一下:
MouseMove 事件中MouseEventArgs 的X 和Y 属性是屏幕左上角的屏幕坐标(0,0)。
像PictureBox 控件这样的许多控件都包含一个PointToClient 方法,它将屏幕坐标转换为本地控件的坐标,其中(0,0) 将是控件的左上角。
因此,例如,如果您的控件放置在屏幕上的位置 (60, 75) 并且右下角坐标为 (135, 120)。如果您的鼠标位于控件上方,并且距离左侧 10 像素,距离顶部 20 像素,则 MouseMove 事件中 MouseEventArgs 的 X 和 Y 属性将为:X = 70 和 @987654333 @ = 95。如果使用PointToClient将这些转换为图片框控件的内部坐标,则表明X = 10 和Y = 20。
现在,如果您想要一个 TrackBar 来显示鼠标的 X 坐标在某个控件上的位置的相对指示,您可以按如下方式计算它:
// Set the minimum and maximum of the trackbar to 0 and 100 for a simple percentage.
trackBar1.Minimum = 0;
trackBar1.Maximum = 100;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = pictureBox1.PointToClient(new Point(e.X, e.Y)).X * 100 / pictureBox1.Width;
如果您想让轨迹栏使用屏幕坐标来跟踪鼠标在某个控件上的 X 坐标的相对位置,您可以按如下方式计算:
// Set the minimum and maximum values of the track bar to the screen coordinates of the
// control we want to track.
trackBar1.Minimum = pictureBox1.PointToScreen(0,0).X;
trackBar1.Maximum = pictureBox1.PointToScreen(pictureBox1.Width, 0).X;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = e.X;
如果您想让轨迹栏使用某个控件的内部坐标来跟踪鼠标在该控件上的 X 坐标的内部位置,您可以按如下方式计算:
// Set the minimum and maximum values of the track bar to zero and the width of the
// control we want to track.
trackBar1.Minimum = 0;
trackBar1.Maximum = pictureBox1.Width;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = pictureBox1.PointToClient(new Point(e.X, e.Y)).X;
// or - not recommended - read below.
trackBar1.Value = e.X - pictureBox1.Left;
现在,有一个警告,那就是如果您将控件放在其他控件中,例如将面板放在面板中的面板中,等等。那么另一个控件中的控件的“世界”坐标是基于它们的父控件中的位置。这就是为什么通过PointToClient 使用控件的内部坐标和通过PointToScreen 使用内部坐标的屏幕坐标是一个好主意的原因,因为否则您将不得不向上遍历所有容器,直到到达屏幕,一直跟踪Top 和Left 坐标。
我希望这能回答你的问题。