WinForms Various DPI Layouts

Somehow, the forms and controls created with Visual Studio and the designer have great ability to scale depending on the current DPI / font size of Windows. One part of my user interface is a tab control consisting of dynamic pages and labels / inputs created depending on the user's choice. When they are created, they use hard coded sizes that look right for 96 DPI.

Is there an automatic way in .Net to take these generated controls and do the same resizing that is done for the designer-created controls? I would like to avoid scaling the controls since this is older code that is not supported.

+4
source share
3 answers

Well, this is technically easy to do by repeating the tab “Manage” tabs and multiplying the “Point” and “Size” properties by the scaling factor. But it becomes terribly difficult if you start to consider the properties of Dock and Anchor.

On the contrary, the easiest approach is to let the Form class scalers do the work for you. You will need to add controls to the tab pages before the download event fires. Do it in the constructor.

Quick tip to avoid the pain of switching the DPI setting to check your code: add this to the form constructor to trigger the scaling logic:

protected override void OnLoad(EventArgs e) {
    this.Font = new Font(this.Font.FontFamily, this.Font.Size * 120 / 96);
    base.OnLoad(e);
}
+9
source
0

I solved the same problem, with controls created at runtime as needed by doing what designer.cs does:

void CreateRuntimePanel()
{
    //instantiate controls here...

    //suspend layouts
    //begin inits

    this.SuspendLayout();

    //set control properties here

    //before adding any control to form Controls collection, do this
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

    //add controls to form Controls collection here

    //resume layouts
    //end inits

    this.ResumeLayout(false);  
}
0
source

All Articles