winform使用Resize设置窗口控件大小按照窗口大小等比例缩放
作者:互联网
直接贴代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Winform2 { public partial class Form1 : Form { public float Xvalue; public float Yvalue; bool flag = false; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { foreach (Control control in this.Controls) { control.ForeColor = Color.Red; } } private void Form1_Resize(object sender, EventArgs e) { if (flag) { float newx = (this.Width) / Xvalue; float newy = this.Height / Yvalue; setControls(newx, newy, this); } } private void setControls(float newx, float newy, Control cons) { foreach (Control con in cons.Controls) { 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]) * newy; //改变字体大小 con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) { try { setControls(newx, newy, con); } catch { } } } } private void Form1_Load(object sender, EventArgs e) { Xvalue = this.Width; Yvalue = this.Height; flag = true; setTag(this); } private 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) setTag(con); } } } }
窗口加载两个事件即可。
一个是加载onload事件:用于获取窗口的长和宽的
一个是窗口大小Resize改变事件:当窗口大小改变时触发的事件
标签:控件,窗口,缩放,float,System,newy,using,Font,con 来源: https://www.cnblogs.com/masha2017/p/15131546.html