最新在写个小程序,需要窗体填满各种尺寸的显示器,同时需要同步缩放控件的大小。于是就写了个类,简单的调用一下即可解决问题。
这个类可以同步缩放控件的位置,宽度高度,字体大小。
使用的时候在FormLoad里面绑定一下即可:
public partial class Form1 : Form
{
private ControlResizer Resizer; //定义缩放类 public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//绑定
Resizer=new ControlResizer(this);
} }
控件缩放类的代码:
/// <summary>
/// 同步缩放窗体上控件的大小和字体
/// </summary>
public class ControlResizer
{
class ControlPosAndSize
{
public float FrmWidth { get; set; }
public float FrmHeight { get; set; }
public int Left { get; set; }
public int Top { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public float FontSize { get; set; } } private Form _form; //句柄,大小信息
private Dictionary<int, ControlPosAndSize> _dic = new Dictionary<int, ControlPosAndSize>();
public ControlResizer(Form form)
{
_form = form;
_form.Resize += _form_Resize;//绑定窗体大小改变事件 _form.ControlAdded += form_ControlAdded; //窗体上新增控件的处理
_form.ControlRemoved += form_ControlRemoved; SnapControlSize(_form);//记录控件和窗体大小
} void form_ControlRemoved(object sender, ControlEventArgs e)
{
var key = e.Control.Handle.ToInt32();
_dic.Remove(key);
} //绑定控件添加事件
private void form_ControlAdded(object sender, ControlEventArgs e)
{
var ctl = e.Control;
var ps = new ControlPosAndSize
{
FrmHeight = _form.Height,
FrmWidth = _form.Width,
Width = ctl.Width,
Height = ctl.Height,
Left = ctl.Left,
Top = ctl.Top,
FontSize = ctl.Font.Size
};
var key = ctl.Handle.ToInt32();
_dic[key] = ps;
} void _form_Resize(object sender, EventArgs e)
{
ResizeControl(_form);
} private void ResizeControl(Control control)
{
foreach (Control ctl in control.Controls)
{
var key = ctl.Handle.ToInt32();
if (_dic.ContainsKey(key))
{
var ps = _dic[key];
var newx = _form.Width / ps.FrmWidth;
var newy = _form.Height / ps.FrmHeight; ctl.Top = (int)(ps.Top * newy);
ctl.Height = (int)(ps.Height * newy); ctl.Left = (int)(ps.Left * newx);
ctl.Width = (int)(ps.Width * newx); ctl.Font = new Font(ctl.Font.Name, ps.FontSize * newy, ctl.Font.Style, ctl.Font.Unit); if (ctl.Controls.Count > )
{
ResizeControl(ctl);
} } }
} /// <summary>
/// 创建控件的大小快照,参数为需要记录大小控件的 容器
/// </summary>
private void SnapControlSize(Control control)
{
foreach (Control ctl in control.Controls)
{
var ps = new ControlPosAndSize
{
FrmHeight = _form.Height,
FrmWidth = _form.Width,
Width = ctl.Width,
Height = ctl.Height,
Left = ctl.Left,
Top = ctl.Top,
FontSize = ctl.Font.Size
}; var key = ctl.Handle.ToInt32(); _dic[key] = ps; //绑定添加事件
ctl.ControlAdded += form_ControlAdded;
ctl.ControlRemoved += form_ControlRemoved; if (ctl.Controls.Count > )
{
SnapControlSize(ctl);
} } } }