C# Get a control's position on a form
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 gives me only it's position within it's parent control, but what if my control is inside five nested panels, and I need it's position on the form?
Quick example:
The button btnA is located on coordinates (10,10) inside the panel pnlB.
The panel pnlB is located on coordinates (15,15) inside the form frmC.
I want btnA's location on frmC, which is (25,25).
Can I get this location?
我通常结合使用PointToScreen
和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.
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;
}
链接地址: http://www.djcxy.com/p/58366.html
上一篇: javascript:找到具有多个显示器的屏幕分辨率
下一篇: C#获取控件在表单上的位置