本身寫的winform窗體自適應大小代碼,代碼比較獨立,很適合貼來貼去不會對原有程序形成影響,能夠直接繼承此類或者把代碼複製到本身的代碼裏面直接使用ide
借鑑了網上的一些資料,最後採用重寫WndProc方法,這樣能夠兼顧窗體拖拽調整窗體大小和最大化、最小化方法,並且代碼比較簡練,代碼侵入性較小字體
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; namespace LzRabbit { public class AutoResizeForm : Form { const int WM_SYSCOMMAND = 0X112;//274 const int SC_MAXIMIZE = 0XF030;//61488 const int SC_MINIMIZE = 0XF020;//61472 const int SC_RESTORE = 0XF120; //61728 const int SC_CLOSE = 0XF060;//61536 const int SC_RESIZE_Horizontal = 0XF002;//61442 const int SC_RESIZE_Vertical = 0XF006;//61446 const int SC_RESIZE_Both = 0XF008;//61448 protected override void WndProc(ref Message m) { if (m.Msg == WM_SYSCOMMAND) { switch (m.WParam.ToInt32()) { case SC_MAXIMIZE: case SC_RESTORE: case SC_RESIZE_Horizontal: case SC_RESIZE_Vertical: case SC_RESIZE_Both: if (WindowState == FormWindowState.Minimized) { base.WndProc(ref m); } else { Size beforeResizeSize = this.Size; base.WndProc(ref m); //窗口resize以後的大小 Size afterResizeSize = this.Size; //得到變化比例 float percentWidth = (float)afterResizeSize.Width / beforeResizeSize.Width; float percentHeight = (float)afterResizeSize.Height / beforeResizeSize.Height; foreach (Control control in this.Controls) { //按比例改變控件大小 control.Width = (int)(control.Width * percentWidth); control.Height = (int)(control.Height * percentHeight); //爲了避免使控件之間覆蓋 位置也要按比例變化 control.Left = (int)(control.Left * percentWidth); control.Top = (int)(control.Top * percentHeight); //改變控件字體大小 control.Font = new Font(control.Font.Name, control.Font.Size * Math.Min(percentHeight, percentHeight), control.Font.Style, control.Font.Unit); } } break; default: base.WndProc(ref m); break; } } else { base.WndProc(ref m); } } } }