放大前 放大后


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); // 调整控件的大小和位置}}
}