問題
當屏幕分辨率提高或降低時,原分辨率顯示正常的控件,將變得很小或很大,字體也變得太大或太小。
解決辦法
當分辨率變化時,采用遞歸的方法,對所有的控件放大或縮小。
public static void MainForm_Load(object sender, EventArgs e){// 獲取當前屏幕分辨率Screen screen = Screen.PrimaryScreen;int currentWidth = screen.Bounds.Width;int currentHeight = screen.Bounds.Height;Control t =(Control) sender;if (t.Width > 1700|| t.Width<1000){// 計算寬度和高度的縮放因子float widthScale = (float)currentWidth / 1920;float heightScale = (float)currentHeight / 1080;// 應用縮放因子ScaleControls((Control)sender, widthScale, heightScale);}}public static void ScaleControls(Control parentControl, float widthScale, float heightScale){foreach (Control control in parentControl.Controls){// 調整控件的大小和位置control.Left = (int)(control.Left * widthScale);control.Top = (int)(control.Top * heightScale);control.Width = (int)(control.Width * widthScale);control.Height = (int)(control.Height * heightScale);if (control.Width > 1700){// 調整字體大小control.Font = new Font(control.Font.FontFamily, control.Font.Size * Math.Min(widthScale, heightScale));}elsecontrol.Font = new Font("宋體", 9);// 遞歸處理子控件if (control.HasChildren){ScaleControls(control, widthScale, heightScale);}}