winfrom窗体控件自适变化
作者:互联网
直接上代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WindowsForms家用汽车 12 { 13 public partial class Form2 : Form 14 { 15 16 public Form2() 17 { 18 InitializeComponent(); 19 } 20 private float X;//当前窗体的宽度 21 private float Y;//当前窗体的高度 22 23 /// <summary> 24 /// 将控件的宽,高,左边距,顶边距和字体大小暂存到tag属性中 25 /// </summary> 26 /// <param name="cons">递归控件中的控件</param> 27 private void setTag(Control cons) 28 { 29 foreach (Control con in cons.Controls)//循环窗体中的控件 30 { 31 con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size; 32 if (con.Controls.Count > 0) 33 setTag(con); 34 } 35 } 36 37 /// <summary> 38 /// 根据窗体大小调整控件大小 39 /// </summary> 40 /// <param name="newx">窗体宽度缩放比例</param> 41 /// <param name="newy">窗体高度缩放比例</param> 42 /// <param name="cons">随窗体改变控件大小</param> 43 private void setControls(float newx, float newy, Control cons) 44 { 45 //遍历窗体中的控件,重新设置控件的值 46 foreach (Control con in cons.Controls) 47 { 48 49 string[] mytag = con.Tag.ToString().Split(new char[] { ':' });//获取控件的Tag属性值,并分割后存储字符串数组 50 float a = System.Convert.ToSingle(mytag[0]) * newx;//根据窗体缩放比例确定控件的值,宽度 51 con.Width = (int)a;//宽度 52 a = System.Convert.ToSingle(mytag[1]) * newy;//高度 53 con.Height = (int)(a); 54 a = System.Convert.ToSingle(mytag[2]) * newx;//左边距离 55 con.Left = (int)(a); 56 a = System.Convert.ToSingle(mytag[3]) * newy;//上边缘距离 57 con.Top = (int)(a); 58 Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小 59 con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); 60 if (con.Controls.Count > 0) 61 { 62 setControls(newx, newy, con); 63 } 64 } 65 }
//加载事件 66 private void Form2_Load_1(object sender, EventArgs e) 67 { 68 69 X = this.Width;//获取窗体的宽度 70 Y = this.Height;//获取窗体的高度 71 setTag(this);//调用方法 72 }
//闪电属性里的Resize 73 private void Form2_Resize_1(object sender, EventArgs e) 74 { 75 float newx = (this.Width) / X; //窗体宽度缩放比例 76 float newy = (this.Height) / Y;//窗体高度缩放比例 77 setControls(newx, newy, this);//随窗体改变控件大小 78 } 79 } 80 }
最大化图片效果也一样
标签:控件,winfrom,System,newy,窗体,using,自适,con 来源: https://www.cnblogs.com/hyh749/p/16449769.html