1、问题分析web
winform程序在不一样分辨率下产生界面混乱的主要缘由是,默认状况下winform程序的坐标是基于Point(点)的,Point与DPI(分辨率,每英寸所打印点数)相关。当DPI发生变化时,显示在界面上的尺寸根据DPI自动变化,致使界面与设计之初产生错乱。c#
2、解决方案函数
方案1 利用AutoScaleMode 属性,将窗体的AutoScaleMode 属性设置为Dpi。布局
Dpi:根据显示分辨率控制缩放。经常使用分辨率为 96 和 120 DPI。 字体
Font:根据类使用的字体(一般为系统字体)的维度控制缩放。 this
Inherit:根据类的父类的缩放模式控制缩放。若是不存在父类,则禁用自动缩放。 spa
None:禁用自动缩放。设计
方案2 借鉴web程序中以pixel(像素)为经常使用单位,在winform程序中使用像素来定位,在Form的构造函数中将窗体的AutoScaleMode 属性设置为Font。code
private void InitializeComponent() { //设定按字体来缩放控件 this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; //设定字体大小为12px this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134))); }
方案3 记录下1920*1080分辨率下工做区域的Width和Height,记做DefaultWidth和DefaultHeight,用改变分辨率以后的工做区域的Width和Height去分别除DefaultWidth和DefaultHeight,获得缩放比例,再调整主界面和各控件的缩放。orm
public class AutoReSizeForm { static float SH { get { return (float)Screen.PrimaryScreen.Bounds.Height / DefaultHeight; } } static float SW { get { return (float)Screen.PrimaryScreen.Bounds.Width / DefaultWidth; } } public static void SetFormSize(Control fm) { fm.Location = new Point((int)(fm.Location.X * SW), (int)(fm.Location.Y * SH)); fm.Size = new Size((int)(fm.Size.Width * SW), (int)(fm.Size.Height * SH)); fm.Font = new Font(fm.Font.Name, fm.Font.Size * SH,fm.Font.Style,fm.Font.Unit,fm.Font.GdiCharSet,fm.Font.GdiVerticalFont); if (fm.Controls.Count!=0) { SetControlSize(fm); } } private static void SetControlSize(Control InitC) { foreach (Control c in InitC.Controls) { c.Location = new Point((int)(c.Location.X * SW), (int)(c.Location.Y * SH)); c.Size = new Size((int)(c.Size.Width * SW), (int)(c.Size.Height * SH)); c.Font = new Font(c.Font.Name, c.Font.Size * SH, c.Font.Style, c.Font.Unit, c.Font.GdiCharSet, c.Font.GdiVerticalFont); if (c.Controls.Count != 0) { SetControlSize(c); } } } }
3、方案分析
方案1和方案2存在必定问题,一方面,在MSDN里有一条警告是不支持在同一窗口里将DPI模式和Font模式混合使用;另外一方面,根据网上的实际经验,自动放缩和窗口布局的Dock、Anchor有时也会有冲突,也就是说目前采用方案1和方案2的自动放缩功能仍不够理想。
方案3的效果有待进一步探究。