前言
在使用 Winform 开发过程中,经常发些因为显示器分辨率、窗体大小改变,控件却不能自适应变化,几经查找资料,和大佬的代码。经过细小修改,终于可以让窗体在外界影响下,窗体内背景图片、控件都会自适应变化大小(类似于网页的响应式)。
代码
完整代码如下:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace AutoSizeForm
{
public partial class FrmMain : Form
{
private float X;
private float Y;
public FrmMain()
{
InitializeComponent();
}
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);
}
}
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]) * Math.Min(newx, newy);
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
if (con.Controls.Count > 0)
{
SetControls(newx, newy, con);
}
}
}
//窗体Resize事件
private void FrmMain_Resize(object sender, EventArgs e)
{
float newx = Width / X;
float newy = Height / Y;
SetControls(newx, newy, this);
Text = Width.ToString() + " " + Height.ToString();
}
//窗体Load事件
private void FrmMain_Load(object sender, EventArgs e)
{
Resize += new EventHandler(FrmMain_Resize);
X = Width;
Y = Height;
SetTag(this);
FrmMain_Resize(new object(), new EventArgs());//x,y可在实例化时赋值,最后这句是新加的,在MDI时有用
}
}
}
注意:在使用过程当中发现画面卡顿,可以打开窗体属性双缓存(DoubleBuffered属性改为True)。