放大前? 放大后


?1.定義當前窗體的寬度和高度
private float x;//定義當前窗體的寬度private float y;//定義當前窗臺的高度
2.接收當前窗體的尺寸大小
x = this.Width;//存儲原始寬度y=this.Height;//存儲原始高度setTag(this);//為控件設置 Tag 屬性
3.聲明方法,獲取控件中的每個尺寸
private void setTag(Control control){foreach(Control con in control.Controls){//Tag屬性 寬度 高度 左邊緣 頂部 字體大小con.Tag=con.Width+";"+con.Height+";"+con.Left+";"+con.Top+";"+con.Font.Size;if(con.Controls.Count > 0 ){setTag(con); //遞歸為子控件設置 Tag}}}
4.遍歷控件尺寸,拿新的尺寸進行比例擴大
private void setControls(float newx,float newy,Control control)
{foreach(Control con in control.Controls){if(con.Tag!=null){string[]mytag=con.Tag.ToString().Split(';');con.Width = Convert.ToInt32(float.Parse(mytag[0])*newx);con.Height = Convert.ToInt32(float.Parse(mytag[1])*newy);con.Left = Convert.ToInt32(float.Parse(mytag[2]) * newx);con.Top = Convert.ToInt32(float.Parse(mytag[3]) * newy);float currrentSize=float.Parse(mytag[4])*newy;// Font.Unit 返回的是一個度量單位con.Font=new Font(con.Font.Name,currrentSize,con.Font.Style,con.Font.Unit);if(con.Controls.Count > 0 ){setControls(newx,newy,con);//遞歸調整子控件的大小和位置}}}
}
5.窗體尺寸變化事件
private void Form1_Resize(object sender, EventArgs e)
{float newx = this.Width / x; // 計算寬度的縮放比例float newy = this.Height / y; // 計算高度的縮放比例setControls(newx,newy,this); // 調整控件的大小和位置
}
整體代碼
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 _03.resizeForm
{public partial class Form1 : Form{private float x;//定義當前窗體的寬度private float y;//定義當前窗臺的高度public Form1(){InitializeComponent();x = this.Width;//存儲原始寬度y=this.Height;//存儲原始高度setTag(this);//為控件設置 Tag 屬性}private void setTag(Control control){foreach(Control con in control.Controls){con.Tag=con.Width+";"+con.Height+";"+con.Left+";"+con.Top+";"+con.Font.Size;if(con.Controls.Count > 0 ){setTag(con); //遞歸為子控件設置 Tag}}}private void setControls(float newx,float newy,Control control){foreach(Control con in control.Controls){if(con.Tag!=null){string[]mytag=con.Tag.ToString().Split(';');con.Width = Convert.ToInt32(float.Parse(mytag[0])*newx);con.Height = Convert.ToInt32(float.Parse(mytag[1])*newy);con.Left = Convert.ToInt32(float.Parse(mytag[2]) * newx);con.Top = Convert.ToInt32(float.Parse(mytag[3]) * newy);float currrentSize=float.Parse(mytag[4])*newy;// Font.Unit 返回的是一個度量單位con.Font=new Font(con.Font.Name,currrentSize,con.Font.Style,con.Font.Unit);if(con.Controls.Count > 0 ){setControls(newx,newy,con);//遞歸調整子控件的大小和位置}}}}private void Form1_Resize(object sender, EventArgs e){float newx = this.Width / x; // 計算寬度的縮放比例float newy = this.Height / y; // 計算高度的縮放比例setControls(newx,newy,this); // 調整控件的大小和位置}}
}