C#获取控件在表单上的位置

Erl*_* D. 65 c# controls winforms

当控件可能在其他控件(如Panel)中时,有没有办法检索控件在窗体中的位置?

控件的Left和Top属性只给出了它在父控件中的位置,但如果我的控件位于五个嵌套面板中,我需要它在窗体上的位置怎么办?

快速举例:

按钮btnA位于面板pnlB内的坐标(10,10)上.
面板pnlB位于形式frmC内的坐标(15,15)上.

我想要btnA在frmC上的位置,这是(25,25).

我可以获得这个位置吗?

Fre*_*örk 89

我通常结合PointToScreenPointToClient:

Point locationOnForm = control.FindForm().PointToClient(
    control.Parent.PointToScreen(control.Location));
Run Code Online (Sandbox Code Playgroud)

  • 这是'真正的绝对位置'http://stackoverflow.com/questions/4998076/getting-the-location-of-a-control-relative-to-the-entire-screen (7认同)
  • @strongriley`control.PointToScreen(Point.Empty)`给出了相对于屏幕的位置,而答案给出了具有顶级表格重新定位的位置. (5认同)
  • 这与`control.PointToScreen(Point.Empty);`有什么不同? (4认同)

Raj*_*ore 11

您可以使用controls PointToScreen方法获取相对于屏幕的绝对位置.

你可以使用Forms PointToScreen方法,并使用基本数学,获得控件的位置.


noi*_*ss2 7

我通常这样做..每次都工作..

var loc = ctrl.PointToScreen(Point.Empty);
Run Code Online (Sandbox Code Playgroud)


Han*_*ing 6

你可以走过父母,注意他们在父母的位置,直到你到达表格.

编辑:像(未经测试)的东西:

public Point GetPositionInForm(Control ctrl)
{
   Point p = ctrl.Location;
   Control parent = ctrl.Parent;
   while (! (parent is Form))
   {
      p.Offset(parent.Location.X, parent.Location.Y);
      parent = parent.Parent;
   }
   return p;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

Supergeek,你的非递归函数没有产生正确的结果,但我的确如此.我相信你的增加了太多了.

private Point LocationOnClient(Control c)
{
   Point retval = new Point(0, 0);
   for (; c.Parent != null; c = c.Parent)
   { retval.Offset(c.Location); }
   return retval;
}
Run Code Online (Sandbox Code Playgroud)