Search code examples
c#.netwinformsuser-interfacedocking

Resizing GUI elements with form resize


I have the following form:

form:

All the labels for the textboxes should stay on the left side of the form where they are. The top two textboxes should stay close to the top and left of the form, but should change in width according to the width of the form as it is resized.

The top edge of the multiline textbox should stay in the same place relative to the top of the form, as should the left edge. It should resize according to the size of the form.

Each of the buttons should stay in the corners where they are.

When the form height is decreased, the multiline textbox should be "squashed". The checkboxes should also stay in the same position.

I have tried numerous approaches to achieve this, but none had the desired effect. This included tablelayout panels, and anchoring the various elements inside them. I have figured out that the buttons, and the top two textboxes may not need to be placed inside a tablelayout, and simply use anchors. I have successfully achieved this by anchoring button1 to the left and bottom, and button2 to the right and bottom. The field1...field3 labels are also in the appropriate positions, and stay where they should be when the form is resized. These labels are anchored to the top and left currently.


Solution

  • You should be able to do that by anchoring the controls this way:

    • 'field1' and 'field2' text boxes: Left, right, and top;

    • 'field3' text box: Left, right, top, and bottom;

    • 'checkBox1' and 'checkBox2': Left and bottom;

    • 'button1': Left and bottom (you got this one already);

    • 'button2': Right and bottom (you got this one too).

    Your labels are probably fine as-is.

    You've probably figured out the anchors already, but basically: if you set the right anchor on a control, you're saying that you want the right side of that control to maintain the same distance from the right side of its container. If the control is not inside a panel, that will be the right side of the form. So, if the 'field1' text box is eight units from the right side of the form in the designer, it will stay eight units from the right side no matter how you resize the form at run time. If you anchor the left and right sides, it will stretch as you resize, since that is the only way to maintain the same distances on both sides.

    You'll also want to set a 'MinimimSize' for the form, to prevent the bottom controls from overlapping the top controls when the form size is reduced.