Keep controls centered on resizable form
When dealing with resizable forms, managing layout can be achieved via the
Dock properties or using a layout panel. However, sometimes the design requires that certain controls stay centered, regardless of the parent form’s size. Luckily, a simple solution exists that does not involve writing centering code and handling resizing events.
Consider the following design requirement:
- Form must contain several pages.
- Each page will be implemented as a user control.
- Each user control will fill entire tab page
We will create a form with a tab control that will cover entire client area (as seen on the image below). This design is commonly used when designing the options dialog or when creating a wizard.
Each page is created as a separate user control and each page may contain different number of controls. Since form is resizable, there is no fixed page size and layout must be carefully crafted. The design time layout will be resized to fit the parent control (in this case, a tab control page).
When we run this application, the resulting look may not satisfy user expectations (seen on the image below). Certain controls can be stretched to fill entire area (like
TreeControl, etc.) and they can be set to
DockStyle.Fill to maintain a certain look across all sizes since they fill most of the client area. But certain control such as
ComboBox look ridiculous when stretched. They can be anchored but doing that may leave the form to look empty.
Centering such controls or set of those controls (e.g. login set of controls) makes more sense. To do that, do the following:
- Enlarge user control in the design view to make sure that all controls can be placed and that their layout can be designed.
- Add all controls that are required for the page
- Resize and reorder all controls to create perfect group layout.
- Select all controls (either via mouse or via the keyboard shortcut
- Click on the “Center Horizontally” button
- Click on the “Center Vertically” button.
- Set the
Anchorproperty for all controls to
Layout mechanics can be entirely created in the design view using the supplied set of properties and layout panels. Zero lines of code must be written for certain layouts which is certainly a benefit in the long term.