在使用 Winform 開發過程當中,常常發些由於顯示器分辨率、窗體大小改變,控件卻不能自適應變化,幾經查找資料,和大佬的代碼。通過細小修改,終於能夠讓窗體在外界影響下,窗體內背景圖片、控件都會自適應變化大小(相似於網頁的響應式)。緩存
完整代碼以下:this
using System; using System.Drawing; using System.Windows.Forms; namespace AutoSizeForm { public partial class FrmMain : Form { private float X; private float Y; public FrmMain() { InitializeComponent(); } 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); } } 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]) * Math.Min(newx, newy); con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) { SetControls(newx, newy, con); } } } //窗體Resize事件 private void FrmMain_Resize(object sender, EventArgs e) { float newx = Width / X; float newy = Height / Y; SetControls(newx, newy, this); Text = Width.ToString() + " " + Height.ToString(); } //窗體Load事件 private void FrmMain_Load(object sender, EventArgs e) { Resize += new EventHandler(FrmMain_Resize); X = Width; Y = Height; SetTag(this); FrmMain_Resize(new object(), new EventArgs());//x,y可在實例化時賦值,最後這句是新加的,在MDI時有用 } } }
注意:在使用過程中發現畫面卡頓,能夠打開窗體屬性雙緩存(DoubleBuffered屬性改成True)。spa