Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms autosize vertically while leaving width adjustable?

Tags:

winforms

Is it possible to use WinForms layout engine to set up a form in such a way that the height is adjusted completely automatically to fit the content, but the width would be adjustable by the user?

As an example, consider the following somewhat contrived form:

  • TLP: TableLayoutPanel, with 1 row and 2 columns.
  • label1: Label, contained in the left column. Set Text to something long, AutoSize to false, Dock to Fill.
  • button1: Button, contained in the right column. Set AutoSize to true.
  • Now set the row to "AutoSize", the first column to "100%" and the second column to "AutoSize".
  • Finally, set the whole TLP to AutoSize true, AutoSizeMode to GrowAndShrink.

At this point, the TLP could reasonably be resized horizontally, but WinForms doesn't seem to allow this.

The idea is that the form containing this TLP would grow or shrink vertically based on the width, which the user can change by resizing the window as usual.

like image 691
Roman Starkov Avatar asked Oct 19 '10 14:10

Roman Starkov


2 Answers

Hopefully you have got the solution by now. But in case anybody having a same query, You can set width of Maximum Size Property to the Actual Width of the Form and the Height of MaximumSize to 0.

like image 107
Scotti Avatar answered Sep 27 '22 21:09

Scotti


This is entirely possible. To do this, you have to override SetBoundsCore on your form. In this you can then control the height such that it doesn't change when a resize might want it to. Just store the height you want it to be in a variable and then have your override always set it to that. This way, when you auto-size the height, you save the new height aware before setting form Height and SetBoundsCore will honour that new height.

like image 20
Jeff Yates Avatar answered Sep 27 '22 22:09

Jeff Yates