先看效果
全屏后大小如下图
代码如下
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 WindowsFormsApp1
{
//参考 https://www.bilibili.com/video/BV1xt4y1A7xb/?spm_id_from=333.788.top_right_bar_window_history.content.click&vd_source=e821a225c7ba4a7b85e5aa6d013ac92e
public partial class Form1 : Form
{
private int originalWidth;
private int originalHeight;
public Form1()
{
InitializeComponent();
originalHeight = this.Height;
originalWidth = this.Width;
originalTag(this);
}
/// <summary>
/// 保存各个控件大小
/// </summary>
/// <param name="ctr"></param>
private void originalTag(Control ctr)
{
foreach (Control ct in ctr.Controls)
{
ct.Tag =
ct.Left.ToString() + ":" +
ct.Top.ToString() + ":" +
ct.Width.ToString() + ":" +
ct.Height.ToString() + ":" +
ct.Font.Size.ToString();
if( ct.Controls.Count > 0)
{
originalTag(ct);
}
Console.WriteLine(ct.Name + " -> " + ct.Tag);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_Resize(object sender, EventArgs e)
{
float newWidth = this.Width / (float)originalWidth;
float newHeight = this.Height / (float)originalHeight;
reSetContralSize(newWidth, newHeight, this);
}
/// <summary>
/// 重绘各个控件大小
/// </summary>
/// <param name="newWidth"></param>
/// <param name="newHeight"></param>
/// <param name="ctr"></param>
private void reSetContralSize( float newWidth, float newHeight, Control ctr)
{
foreach (Control ct in ctr.Controls)
{
if( ct.Tag != null)
{
string[] tagtmp= ct.Tag.ToString().Split(':');
ct.Left = Convert.ToInt32(Convert.ToSingle((string)tagtmp[0]) * newWidth);
ct.Top = Convert.ToInt32(Convert.ToSingle((string)tagtmp[1]) * newHeight);
ct.Width = Convert.ToInt32(Convert.ToSingle((string)tagtmp[2]) * newWidth);
ct.Height = Convert.ToInt32(Convert.ToSingle((string)tagtmp[3]) * newHeight);
ct.Font = new Font(ct.Font.Name,Convert.ToInt32(Convert.ToSingle((string)tagtmp[4]) * newHeight));
if( ct.Controls.Count > 0)
{
reSetContralSize(newWidth, newHeight, ct);
}
}
}
}
}
}
此文参考了博主的视频讲解,链接在代码内保留,不懂得可以去查看视频讲解
特此记录
anlog
2022年9月21日