C# Get a control's position on a form
I usually combine PointToScreen
and PointToClient
:
Point locationOnForm = control.FindForm().PointToClient(
control.Parent.PointToScreen(control.Location));
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.
I usually do it like this.. Works every time..
var loc = ctrl.PointToScreen(Point.Empty);
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;
}