C#窗体控件,文字随电脑分辨率自动调整大小
一、在类中添加方法,代码如下:
#region 窗体控件、字体随分辨率调整,自动调整大小 public static void SetTag(Control cons) { foreach (Control con in cons.Controls) { con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size; if (con.Controls.Count > 0) 类.Main.SetTag(con); } } public static void SetControls( float newx, float newy, Control cons) { foreach (Control con in cons.Controls) { try { string [] mytag = con.Tag.ToString().Split( new char [] { ':' }); float a = Convert.ToSingle(mytag[0]) * newx; con.Width = ( int )a; a = Convert.ToSingle(mytag[1]) * newy; con.Height = ( int )(a); a = Convert.ToSingle(mytag[2]) * newx; con.Left = ( int )(a); a = Convert.ToSingle(mytag[3]) * newy; con.Top = ( int )(a); Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy); con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) { 类.Main.SetControls(newx, newy, con); } } catch { } } } #endregion |
注:类中需要引用using System.Drawing;
二、在窗体中声明两个变量
private float X;
private float Y;
三、窗体的两个事件
private void 窗体名称_Load( object sender, EventArgs e) { this .Resize += new EventHandler(窗体名称_Resize); X = this .Width; Y = this .Height; 类.Main.SetTag( this ); 窗体名称_Resize( new object (), new EventArgs()); this .WindowState = FormWindowState.Maximized; } private void 窗体名称_Resize( object sender, EventArgs e) { if (X == 0) { 窗体名称_Load( new object (), new EventArgs()); } else { float newx = ( this .Width) / X; float newy = this .Height / Y; 类.Main.SetControls(newx, newy, this ); } } |
注:如果是子窗体,窗体要设置属性MaximizeBox=True,MinmizeBox=True,Windowstate=Normal
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?