I have a windows form that has a list of controls on one side and a graph on the other. I want a checkbox to hide and show the graph, but to also shrink or grow the form to accommodate it.
I tried using AutoSize=true
for the form, but then the user can't adjust the size of the form (ie expand or shrink the graph to their screen).
Then I tried
private void toggleCheckBox_Click(object sender, EventArgs e)
{
theGraph.Visible = toggleCheckBox.Checked;
// automatically resize the form
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.OnResize(e);
// this will force the form back to its original size
// but without it the user cant adjust the form size
this.AutoSize = false;
}
How can I display the graph and resize the form on demand, but not restrict the users from resizing the form themselves?
The solution I came up with was to save the size, disable the autosize, and then force the size:
private void toggleCheckBox_Click(object sender, EventArgs e)
{
theGraph.Visible = toggleCheckBox.Checked;
// automatically resize the form
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.OnResize(e);
var NewSize = new System.Drawing.Size(this.Width, this.Height);
// this will force the form back to its original size
// allowing the user to adjust the form
this.AutoSize = false;
// force the form back to its new size
this.Size = newSize;
}
Note: For the AutoSize
to work correctly with anchored controls be sure to set a MinimumSize
for the control being toggled so that a desired amount will be visible on the form.