Is there any way to retrieve a control\'s position in a form, when the control may be inside other controls (like Panels)?
The control\'s Left and Top properties giv
You could walk up through the parents, noting their position within their parent, until you arrive at the Form.
Edit: Something like (untested):
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;
}
This is what i've done works like a charm
private static int _x=0, _y=0;
private static Point _point;
public static Point LocationInForm(Control c)
{
if (c.Parent == null)
{
_x += c.Location.X;
_y += c.Location.Y;
_point = new Point(_x, _y);
_x = 0; _y = 0;
return _point;
}
else if ((c.Parent is System.Windows.Forms.Form))
{
_point = new Point(_x, _y);
_x = 0; _y = 0;
return _point;
}
else
{
_x += c.Location.X;
_y += c.Location.Y;
LocationInForm(c.Parent);
}
return new Point(1,1);
}
You can use the controls PointToScreen
method to get the absolute position with respect to the screen.
You can do the Forms PointToScreen
method, and with basic math, get the control's position.