I've been having some trouble scaling controls in my application properly with the form font size. The problem is that the form dynamically adds controls in response to user actions. Any controls that are on the form when the font size is initially set scale perfectly, but those added afterwards have issues. Their font scales properly, but their position and size don't. To see this in action, create a simple project with an empty form and paste in the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SplitContainer split = new SplitContainer();
split.Dock = DockStyle.Fill;
this.Controls.Add(split);
// Group 1
split.Panel1.Controls.Add(NewGroup());
this.Font = new Font(this.Font.FontFamily, this.Font.Size * 2);
// Group 2
split.Panel2.Controls.Add(NewGroup());
split.SplitterDistance = this.Width / 2;
}
public GroupBox NewGroup()
{
GroupBox groupBox = new GroupBox();
groupBox.Size = new System.Drawing.Size(132, 92);
groupBox.Text = "groupBox";
groupBox.SuspendLayout();
Label label = new Label();
label.AutoSize = true;
label.Location = new Point(6, 16);
label.Text = "label";
groupBox.Controls.Add(label);
Button button = new Button();
button.Location = new Point(6, 58);
button.Size = new Size(93, 28);
button.Text = "button";
groupBox.Controls.Add(button);
CheckBox checkBox = new CheckBox();
checkBox.AutoSize = true;
checkBox.Location = new Point(47, 16);
checkBox.Text = "checkBox";
groupBox.Controls.Add(checkBox);
TextBox textBox = new TextBox();
textBox.Location = new Point(6, 34);
textBox.Size = new Size(120, 20);
textBox.Text = "text";
groupBox.Controls.Add(textBox);
groupBox.ResumeLayout();
return groupBox;
}
}
You can see the effect that I'm talking about in the second groupbox added. What can I do to get controls added after the initial size change to scale correctly?
UPDATE
If I change the second NewGroup
call to look like this:
GroupBox group = NewGroup();
split.Panel2.Controls.Add(group);
group.Scale(new SizeF(2.0f, 2.0f));
The result is ALMOST correct. It tends to be off by a pixel or two in a lot of cases, and in complex forms this starts to show up much more visibly. I really need the scaling to be as consistent as possible between controls, so I'd like to avoid this approach.