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();