在创建winform窗口时,常常控件不能随窗口正确比例缩放。
运行窗体如下:
最大化后窗体:
缩小后窗体:
实现方法如下
在form1窗口下添加一个panel工具,在父容器中停靠;
然后在panel容器中放置我们需要的工具;
新建一个 NForm 窗体类,继承默认窗体类 Form ,而原来的 Form1 :Form 窗体类继承的默认窗体类修改为 Form1 :NForm 自定义新建的窗体类。
新建窗体类代码如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class NForm : Form
{
#region 控件缩放
double formWidth;//窗体原始宽度
double formHeight;//窗体原始高度
double scaleX;//水平缩放比例
double scaleY;//垂直缩放比例
Dictionary<string, string> controlInfo = new Dictionary<string, string>();
//控件中心Left,Top,控件Width,控件Height,控件字体Size
/// <summary>
/// 获取所有原始数据
/// </summary>
protected void GetAllInitInfo(Control CrlContainer)
{
if (CrlContainer.Parent == this)
{
formWidth = Convert.ToDouble(CrlContainer.Width);
formHeight = Convert.ToDouble(CrlContainer.Height);
}
foreach (Control item in CrlContainer.Controls)
{
if (item.Name.Trim() != "")
controlInfo.Add(item.Name, (item.Left + item.Width / 2) + "," + (item.Top + item.Height / 2) + "," + item.Width + "," + item.Height + "," + item.Font.Size);
if ((item as UserControl) == null && item.Controls.Count > 0)
GetAllInitInfo(item);
}
}
private void ControlsChangeInit(Control CrlContainer)
{
scaleX = (Convert.ToDouble(CrlContainer.Width) / formWidth);
scaleY = (Convert.ToDouble(CrlContainer.Height) / formHeight);
}
private void ControlsChange(Control CrlContainer)
{
double[] pos = new double[5];//pos数组保存当前控件中心Left,Top,控件Width,控件Height,控件字体Size
foreach (Control item in CrlContainer.Controls)
{
if (item.Name.Trim() != "")
{
if ((item as UserControl) == null && item.Controls.Count > 0)
ControlsChange(item);
string[] strs = controlInfo[item.Name].Split(',');
for (int j = 0; j < 5; j++)
{
pos[j] = Convert.ToDouble(strs[j]);
}
double itemWidth = pos[2] * scaleX;
double itemHeight = pos[3] * scaleY;
item.Left = Convert.ToInt32(pos[0] * scaleX - itemWidth / 2);
item.Top = Convert.ToInt32(pos[1] * scaleY - itemHeight / 2);
item.Width = Convert.ToInt32(itemWidth);
item.Height = Convert.ToInt32(itemHeight);
try
{
item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));
}
catch
{
}
}
}
}
#endregion
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (controlInfo.Count > 0)
{
ControlsChangeInit(this.Controls[0]);
ControlsChange(this.Controls[0]);
}
}
}
}
在Form1.cs文件中修改:
public partial class Form1 : NForm
{
public Form1()
{
InitializeComponent();
GetAllInitInfo(this.Controls[0]);
}
}