C# Get a control's position on a form

前端 未结 9 701
星月不相逢
星月不相逢 2020-11-27 12:10

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

9条回答
  •  臣服心动
    2020-11-27 12:48

    Oddly enough, PointToClient and PointToScreen weren't ideal for my situation. Particularly because I'm working with offscreen controls that aren't associated with any form. I found sahin's solution the most helpful, but took out recursion and eliminated the Form termination. The solution below works for any of my controls visible or not, Form-contained or not, IContainered or not. Thanks Sahim.

    private static Point FindLocation(Control ctrl)
    {
        Point p;
        for (p = ctrl.Location; ctrl.Parent != null; ctrl = ctrl.Parent)
            p.Offset(ctrl.Parent.Location);
        return p;
    }
    

提交回复
热议问题