C# Get a control's position on a form

前端 未结 9 661
星月不相逢
星月不相逢 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 13:01

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 13:02

    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);
            }
    
    0 讨论(0)
  • 2020-11-27 13:04

    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.

    0 讨论(0)
提交回复
热议问题