WinForms Different DPI Layouts

前端 未结 3 985
挽巷
挽巷 2020-12-18 09:33

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 p

相关标签:
3条回答
  • 2020-12-18 10:12

    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);
    }
    
    0 讨论(0)
  • 2020-12-18 10:15

    Have you tried the AutoScaleMode property?

    0 讨论(0)
  • 2020-12-18 10:16

    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);  
    }
    
    0 讨论(0)
提交回复
热议问题