public partial class Form1 : Form
{
float xvalues;
float yvalues;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Resize += new EventHandler(MainForm_Resize); //添加窗体拉伸重绘事件
xvalues = this.Width;//记录窗体初始大小
yvalues = this.Height;
SetTag(this);
}
private void MainForm_Resize(object sender, EventArgs e)//重绘事件
{
float newX = this.Width / xvalues;//获得比例
float newY = this.Height / yvalues;
SetControls(newX, newY, this);
}
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]) * newY;
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
if (con.Controls.Count > 0)
{
SetControls(newX, newY, con);
}
}
}
/// <summary>
/// 遍历窗体中控件函数
/// </summary>
/// <param name="cons"></param>
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);
}
}
}
}
获得屏幕分辨率:
System.Drawing.Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
this.Width = rect.Width;
this.Height =rect.Height;