WinForms Different DPI Layouts

谁都会走 提交于 2019-11-29 07:47:50
Hans Passant

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);
}

Have you tried the AutoScaleMode property?

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);  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!