2

In the Form Load event I'm adding some controls to the Form dynamically.
I use this code to resize the Form to adapt its Size to the its new content:

this.MaximumSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;

It works fine but StartPosition = FormStartPosition.CenterScreen doesn't work as expected:
the Form center position is calculated based on the original size.

Jimi
  • 29,621
  • 8
  • 43
  • 61
North5014
  • 63
  • 7
  • Sure, getting it centered requires handling the difference between the screen size and the window size. You changed the window size, not centered anymore. Add `this.CenterToParent();` to do it again. – Hans Passant Apr 02 '20 at 22:54

1 Answers1

1

My suggestion is to resize the Form using it's PreferredSize property. When you have added new Controls to the Form and these Controls don't fit in client area, the PreferredSize is updated to reflect the new size needed to contain them all, but limited to the Form's MaximumSize you have set.
Then use the CenterToScreen() method to center the Form to the current Screen.

CenterToParent(), suggested by Hans Passant in comments, has the same effect if the Form is not parented to any other Form: i.e., if it's not shown using the .Show(this) method overload; otherwise, it's centered to the Owner Form.

Setting AutoSizeMode = AutoSizeMode.GrowAndShrink (or calling the SetAutoSizeMode() method) and then setting AutoSize = true can have unwanted results. The more visible is that you cannot resize your Form with normal means anymore. The area occupied by a StatusStrip may not be considered etc.

As a note, if your application is not DpiAware, the Screen measures and your Form's Size may be different from what is expected. In case it's not, read about it here:

High DPI support in Windows Forms

These notes about the Screen and VirtualScreen may also be useful:


So, add your controls to the Form (maybe in the Load handler) then:

var screen = Screen.FromHandle(this.Handle);
this.MaximumSize = new Size(screen.WorkingArea.Width, screen.WorkingArea.Height);
this.ClientSize = this.PreferredSize;
this.CenterToScreen();
Jimi
  • 29,621
  • 8
  • 43
  • 61