Files
slz-4/SLZ_4/AutoResizeForm.cs

72 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SLZ_4
{
public class AutoResizeForm : Form
{
private Dictionary<Control, Rectangle> originalRects = new Dictionary<Control, Rectangle>();
private Size originalSize;
public AutoResizeForm()
{
this.Load += (s, e) =>
{
originalSize = this.ClientSize;
StoreOriginalSizes(this);
};
this.Resize += Form_Resize;
}
private void StoreOriginalSizes(Control parent)
{
foreach (Control ctrl in parent.Controls)
{
originalRects[ctrl] = new Rectangle(
ctrl.Left, ctrl.Top, ctrl.Width, ctrl.Height);
if (ctrl.Controls.Count > 0)
StoreOriginalSizes(ctrl);
}
}
private void Form_Resize(object sender, EventArgs e)
{
if (originalSize.Width == 0 || originalSize.Height == 0) return;
float xRatio = (float)ClientSize.Width / originalSize.Width;
float yRatio = (float)ClientSize.Height / originalSize.Height;
foreach (var entry in originalRects)
{
Control ctrl = entry.Key;
Rectangle rect = entry.Value;
ctrl.Left = (int)(rect.Left * xRatio);
ctrl.Top = (int)(rect.Top * yRatio);
ctrl.Width = (int)(rect.Width * xRatio);
ctrl.Height = (int)(rect.Height * yRatio);
// 字体自适应(可选)
if (ctrl.Font != null)
{
if (xRatio > 1 && yRatio > 1)
{
ctrl.Font = new Font(ctrl.Font.FontFamily, ctrl.Font.Size * (float)1.2);
}
else
{
ctrl.Font = new Font(ctrl.Font.FontFamily, ctrl.Font.Size * (float)0.8);
}
}
}
//originalSize.Width = ClientSize.Width;
//originalSize.Height = ClientSize.Height;
}
}
}