Sad Hyena
Sad Hyena

Reputation: 311

How can I link a component's Size to the Window size?

I am making a simple WinForms program.
I would like to link a component's size to the size of the Window.

Let's say the user enlarges or shrinks the Window by dragging it's borders: I would like that a component gets bigger when the Window does and vice versa.

Let's pretend that we have two Buttons, in the center of the Window, side by side: I want to make them the same size filling the entire width of the Window.

How can I do that?

Upvotes: 2

Views: 1161

Answers (1)

Jimi
Jimi

Reputation: 32248

Sample procedure, using a TableLayoutPanel and 2 Buttons:

  • Add a TableLayoutPanel to the Form
    1. Edit the Columns and Rows collections so that you have 2 Columns, both sized at 50% and one Row, set to Autosize.
    2. Set the Location.X of the TableLayoutPanel to 0 and adjust its width to the width of the Form.
    3. Set the TLP Anchor property to Left and Right
    4. Adjust-drag the Row height to be ~twice the size of the Button it will host
  • Add one Button to the Form
    1. Adjust the appearance of the Button as required.
    2. CTRL-Drag the Button to create an exact duplicate
    3. Add the two Buttons to the two cells of the TableLayoutPanel
    4. SHIFT-Select both Buttons and set the Dock property to DockStyle.Fill
    5. You can now adjust the Margin property of the Buttons (still both selected, so the same settings will apply to both) to modify the space between the controls
  • Re-adjust the TableLayoutPanel's only Row height as needed.
  • Extra: if you have only these controls on the Form, you may want to fix the MinimumSize of the Form, to avoid that, when the Form is resized, your controls are shrinked beyond recognition, ruining the overall layout: resize the Form in the Designer to a point where the hosted controls layout is compromised, find a suitable minimum size and use this measure as the Form's MinimumSize property. The MinimumSize can be set using only the Width or the Height measure (e.g., (100, 0)). This limits the Form's Width but not the Height. Or the opposite, of course.

If, when dragging the Buttons inside the TableLayoutPanel, the Buttons are not automatically inserted at the Top-Left position of the cell and instead they appear positioned in a random place, then the TableLayoutPanel has gone rogue and needs to be put down. Delete it and drop another on the Form. Rinse and repeat.

This may happen if you tamper with the layout a bit. Better start over than trying to correct the problem.

TableLayoutPanel Control Overview

Upvotes: 4

Related Questions