views:

326

answers:

2

Somehow forms and controls created through Visual Studio and the designer have the great ability to scale themselves depending on the current DPI/font size of Windows. One portion of my UI is a tab control full of dynamic pages and labels/inputs generated depending on the user's selection. When these are created, they use hard coded sizes that look right for 96 DPI.

Is there an automated way in .Net to take these generated controls and do the same resizing that is performed for the designer generated controls? I'd like to avoid scaling the controls myself as this is older code not easily maintained.

A: 

Have you tried the AutoScaleMode property?

nasufara
Yes, AutoScaleMode is what makes my other controls scale perfectly but it doesn't seem to affect the dynamic controls. I also mimic the Suspend/ResumeLayout and PerformLayout calls used by the designer while generating the controls.
WhoaNow
+3  A: 

Well, it is technically easy to do by iterating the tab pages' Control collection and multiply the Point and Size properties by the scaling factor. But that gets to be awfully tricky once you start to account for the Dock and Anchor properties.

By far the simplest approach is to let the Form class scaling machinery do the job for you. You'll need to add the controls to the tab pages before the Load event runs. Do this in the constructor.

Quick tip to avoid the pain of switching the DPI setting to test your code: add this to your form constructor to invoke the rescaling logic:

protected override void OnLoad(EventArgs e) {
  this.Font = new Font(this.Font.FontFamily, this.Font.Size * 125 / 96);
}
Hans Passant
@nobugz : assuming a variety of different types of tab pages (each type has different internal controls) : could these be pre-defined as UserControls: to get the same benefits of "form class scaling machinery" So : at runtime : if the user creates a new tab page of type #3 : the Controls collection of the new tab page is set to a new instance of UserControl3 docked 'fill which, of course, invokes the 'Load event of the UserControl : in that circumstance will the UserControl also scale properly ? thanks,
BillW
Yes, scaling is implemented by ContainerControl. Like Form, UserControl derives from it.
Hans Passant
@nobuz Thanks, the information I learned from your answer, and confirmation the same applies to UserControls is very valuable !
BillW
+1 for the quick tip!
zaladane