[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Size forms to fit their contents in C#

[Size forms to fit their contents in C#]

This example shows how to size forms to fit their contents. Figuring out how to size forms can be tricky, particularly if a form contains a MenuStrip with LayoutStyle = Flow so the MenuStrip may hold more than one row of menus.

Fortunately you don't need to figure out the necessary size yourself. Instead simply set the form's ClientSize property to the size you want the client area to occupy. The form resizes itself appropriately, allowing room for the menus if necessary.

When you click this program's button, the following code executes.

// Change the form's size and size it to fit. private void btnClickMe_Click(object sender, EventArgs e) { // Move the button to a new location. if (btnClickMe.Location.X != 100) { btnClickMe.Location = new Point(100, 200); } else { btnClickMe.Location = new Point(250, 100); } // Make the form just big enough to hold the button. this.ClientSize = new Size( btnClickMe.Right, btnClickMe.Bottom); }

The code starts by moving its button to a new location. It then sets the form's ClientSize to be just big enough to display the button.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.