开发者

WinForms Different DPI Layouts

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.


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 * 120 / 96);
    base.OnLoad(e);
}


I solved the same issue, 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's Controls collection, do this
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

    //add controls to form's Controls collection here

    //resume layouts
    //end inits

    this.ResumeLayout(false);  
}


Have you tried the AutoScaleMode property?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜