我正在寻找一种方法,可以获取控件相对于其所在窗体的位置,而不是相对于窗体的客户区域左上角的位置。
当然,我可以将所有内容都转换为屏幕坐标,但我想知道是否有更直接的方法来实现这个目的。
当然,我可以将所有内容都转换为屏幕坐标,但我想知道是否有更直接的方法来实现这个目的。
你需要将其转换为屏幕坐标,然后进行一些数学计算。
Point controlLoc = form.PointToScreen(myControl.Location);
现在:
Point relativeLoc = new Point(controlLoc.X - form.Location.X, controlLoc.Y - form.Location.Y);
这将给出相对于表单左上角的位置,而不是相对于表单客户区域的位置。
form.PointToScreen(new Point(0, 0))
,保存结果,然后在需要获取窗口相对坐标时,只需将 X 和 Y 值添加到控件的 Location
中即可。 - Jim MischelPointToScreen
方法来获取窗体客户区域的位置,并从Location的X和Y值中减去偏移量。对此我感到抱歉。 - Jim MischelRectangle screenCoordinates = control.Parent.ClientToScreen(control.ClientRectangle);
Rectangle formCoordinates = this.ScreenToClient(screenCoordinates);
看起来答案是没有直接的方法来做到这一点。
(正如我在问题中所述,我正在寻找一种不使用屏幕坐标的方法。)
如果您的控件位于许多其他设置为自动调整大小的控件内部,则上述任何答案都无法帮助您,即:
Form -> FlowLayoutPanel -> Panel -> Panel -> Control
所以我已经用不同的逻辑编写了自己的代码,但是我不知道如果父控件之间使用了一些对接,结果会是什么样子。我猜测在这种情况下需要涉及边距和填充。
public static Point RelativeToForm(this Control control)
{
Form form = control.FindForm();
if (form is null)
return new Point(0, 0);
Control parent = control.Parent;
Point offset = control.Location;
while (parent != null)
{
offset.X += parent.Left;
offset.Y += parent.Top;
parent = parent.Parent;
}
offset.X -= form.Left;
offset.Y -= form.Top;
return offset;
}
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Cambia
{
public static class ControlExtensions
{
public static Point FormRelativeLocation(this Control control, Form form = null)
{
if (form == null)
{
form = control.FindForm();
if (form == null)
{
throw new Exception("Form not found.");
}
}
Point cScreen = control.PointToScreen(control.Location);
Point fScreen = form.Location;
Point cFormRel = new Point(cScreen.X - fScreen.X, cScreen.Y - fScreen.Y);
return cFormRel;
}
}
}
cFormRel
。 - Don Shrout