Winform控件自适应窗体大小
思路[参考他人]:
1>保存窗体的初始宽度和高度;
2>保存窗体内所有控件的初始宽度,初始高度和坐标;
3>窗体的Resize事件触发时,计算新的Size和初始Size的比例prec;
4>遍历窗体内所有控件,将其的Size和坐标乘以prec;
代码:
窗体注册,保存窗体及其所有控件的初始尺寸,编写Resize事件逻辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void Register(Control con) { SetFlag(con); con.Tag = con.Width + ";" + con.Height + ";" + con.Top + ";" + con.Left; con.Resize += ( object sender, EventArgs e) => { Control c = (sender as Control); int initX = Convert.ToInt32(c.Tag.ToString().Split( ';' )[0]); int initY = Convert.ToInt32(c.Tag.ToString().Split( ';' )[1]); float x = c.Width / initX; float y = c.Width / initY; ReControlSize(x, y, c); }; } |
SetFlag函数:
1 2 3 4 5 6 7 8 | static void SetFlag(Control con) { foreach (Control c in con.Controls) { c.Tag = c.Width + ";" + c.Height + ";" + c.Top + ";" + c.Left; SetFlag(c); } } |
ReControlSize函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void ReControlSize( float x, float y,Control obj) { foreach (Control con in obj.Controls) { if (con.Tag == null ) continue ; string [] tags = con.Tag.ToString().Split( ';' ); con.Width = Convert.ToInt32(Convert.ToSingle(tags[0]) * x); con.Height = Convert.ToInt32(Convert.ToSingle(tags[1]) * y); con.Top = Convert.ToInt32(Convert.ToSingle(tags[2]) * y); con.Left = Convert.ToInt32(Convert.ToSingle(tags[3]) * x); ReControlSize(x, y, con); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!