mathgenius
mathgenius

Reputation: 513

Sizing form to Control.Bounds.Bottom creates unexpected result

I have a windows form, in which I have a Tab Control in which I have other controls.

Since the amount of controls is dynamic and I want to size the Form just right I have this piece of code:

        int w = 0;
        int h = 0;
        foreach (Control x in Tab_Control.Controls)
        {
            if (x.Bounds.Right > w) w = x.Bounds.Right;
            if (x.Bounds.Bottom > h) h = x.Bounds.Bottom;
        }
        Tab_Control.Size = new Size(w, h);
        Form1.Size = new Size(w, h);

While this sets the form width just right its height crops two controls on the bottom. I thought it might be because the positions are relative to the parent control, but when I used "PointToScreen(Point.Empty)" to get some real coordinates I found the difference to be 21 pixels, which didn't help much.

So I am wondering why setting the form height to h ends up being too short.

Upvotes: 0

Views: 98

Answers (2)

Hans Passant
Hans Passant

Reputation: 941217

Simply set the ClientSize property instead.

Better yet is to write no code at all. Set the form's AutoSize property to True, AutoSizeMode to GrowAndShrink. You surely prefer setting the Margin property on control(s) at the bottom and the right so there's a decent space between the control and the border.

Upvotes: 2

ChrisF
ChrisF

Reputation: 137108

The discrepancy is due to the size of the form's title bar.

You are calculating the size required by the controls correctly, but you are then setting the overall size of the window - which includes the title bar - to that height.

You'll need to add on the height of the title bar to the size you are calculating.

You can get the height of the title bar from the CaptionHeight property in System.Windows.Forms.SystemInformation

If that doesn't cover all of the discrepancy then look at the form's border thickness to see if you need to take that into account as well

Upvotes: 3

Related Questions