Winform 窗體自適應
阿新 • • 發佈:2021-01-19
前言
在使用 Winform 開發過程中,經常發些因為顯示器解析度、窗體大小改變,控制元件卻不能自適應變化,幾經查詢資料,和大佬的程式碼。經過細小修改,終於可以讓窗體在外界影響下,窗體內背景圖片、控制元件都會自適應變化大小(類似於網頁的響應式)。
程式碼
完整程式碼如下:
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)。