WinForms AutoLayout Basics – Button
I know. I know. You know everything there is to know about buttons. But, please bear with me. In my last post, I created a form that had two buttons, OK and Cancel. The form was very simple, but there are actually issues with the buttons on the form. The main problem is that the buttons don’t AutoSize. When the form is localized and “Cancel” turns into something that has 20 letters, the button size won’t change automatically. The new text will be truncated.
So how do we get the buttons ready for localization? Let’s take the previous post’s example as a starting point and test it out.
- In the Load event for the form, add the following line of code:
buttonCancel.Text = “xxxxx Cancel xxxxx”;
- Now run the form. Notice that the buttonCancel’s size did not change and that the text was truncated.
Let’s fix it.
- Change the AutoSize property of buttonCancel and buttonOK to true.
- Run the form again and see what happens now. Notice that buttonCancel got larger. This happened because the AutoSize property of the button was true and the column it is in is set to AutoSize. Notice also that buttonOK was moved over to make room for buttonCancel. In fact, the entire first column shrank to make room. This is because the first column is set to Percent. Any change in the AutoSize or Absolute style columns is absorbed by the Percent columns.
- In the Load event for the form, add the following line of code (do not remove or change the first line you added):
buttonCancel.Text = “Cancel”;
- Run the form again and see what happens now. Notice that buttonCancel is bigger than it needs to be. This is because the AutoSizeMode is GrowOnly. The button will only grow and never shrink to fit its contents. It is still big enough for the text “xxxxx Cancel xxxxx”.
Let’s fix it.
- Change the AutoSizeMode property of buttonCancel and buttonOK to GrowAndShrink.
- Run the form again and see what happens now. Notice that the buttons start off smaller. In fact, they shrank in the designer as well. This is exactly what we told the buttons to do but it isn’t very pretty. Typically you want the buttons to have a little padding around the text and a minimum size.
Let’s fix it.
- Change the Padding property of buttonCancel and buttonOK to 10,0,10,0. This gives a little padding around to the left and right of the text.
- Change the MinimumSize property of buttonCancel and buttonOK to 75,23. This is the default size that buttons are created with and is typically the smallest you would want a button to be.
- Run the form again and see what happens now. Now the buttons shrink only to the minimum size that we gave them.
To summarize, Buttons should be put into a TableLayoutPanel and have the following properties set:
AutoSize = true
AutoSizeMode = GrowAndShrink
MinimumSize = (75, 23)
Padding = (10, 0, 10, 0)
Of course, the above suggestions don’t hold true for every dialog, but probably most.