Size a form to fit its contents in C#

Figuring out big to make a form so it fits its contents can be tricky, particularly if it contains a MenuStrip with LayoutStyle = Flow so the MenuStrip may hold more than one row of menus. Fortunately making a form fit its contents is much easier: simply set its 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(200, 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.