Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...