winform使用Resize設定視窗控制元件大小按照視窗大小等比例縮放
阿新 • • 發佈:2021-08-12
直接貼程式碼:
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 { publicfloat 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改變事件:當視窗大小改變時觸發的事件