6

In Windows Forms, when I position a label control at Y=0 inside a groupbox, then the label intersects with the title text on top of the groupbox.

How can I get the usable area within the Groupbox, i.e. the are that's not obstructed by the title text of the box?

Setting control.Y = groupBox.Padding.Top doesn't work. And Groupbox.ClientRectangle doesn't take the text into account either.

Explanation

Edit: There is an easy hack to get that inner rectangle: Simply position one Labelin the GroupBox, and set it's Dock property to Fill. Then you can get the relevant information (Top/Bottom/Left/Right) from the Panel, or simply use the panel directly to add your child controls. However, I'd still like to know how to get those coordinates without such hacks.

1
  • 1
    There's no property for this, it is always eyeballed in the designer. You'll need to measure the text height yourself, TextRenderer.MeasureText(). Jan 15, 2013 at 20:57

2 Answers 2

3

Try using the DisplayRectangle property:

The DisplayRectangle property returns the client rectangle of the display area of the control. For the base control class, this is equal to the client rectangle. However, inheriting controls might want to change this if their client area differs from their display area. The display rectangle is the smallest Rectangle that encloses a control and is used to lay out controls.

Example:

label1.Location = groupBox1.DisplayRectangle.Location;
2
  • 1
    The DisplayRectangle returned does not respect the lower bounds of the Text property of the GroupBox when you have changed the font to 20 em via code. Mar 10, 2016 at 17:23
  • @JohnShedletsky Still works for me with groupBox1.Font = new Font(groupBox1.Font.FontFamily, 20);, then I did groupBox1.Text = groupBox1.DisplayRectangle.ToString(); and it returns a location of (3, 34). Placing a panel inside that group box at that location did not overlapped the enlarged caption. You will have to give me code that duplicates your issue.
    – LarsTech
    Mar 10, 2016 at 17:31
1

Quite old thread, but here is what I use for my controls :

label1.Location = new Point(0,(int)(groupBox1.Font.Size)*2);

HeaderWithBigText

HeaderWithSmallText

And this is how it looks with different text sizes.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.