winform窗体拉伸重绘代码
gitub仓库https://github.com/impPDX/WinForm-
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 GDIDemo1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
float xvalues;
float yvalues;
private void Form2_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);
}
}
}
}
}