c# winform 根据窗体自动调整控件

一、概述

本文要实现的功能是:当窗体最大化时,控件的大小可以随窗体一起变化。开发环境,vs2010 c# winform,窗体名称采用默认的Form1.

2、把调整控件大小的方法放到一个类中:FormSetSelfAuto.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing; namespace Kaifafanli
{
public class FormSetSelfAuto
{
private float X;
private float Y;
public float _x
{
set { X = value; }
}
public float _y
{
set { Y = value; }
}
//获取控件的width,height,left,top,字体的大小值,存放在控件的tag属性中
public 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>)
{
setTag(con);
}
}
}
//根据窗体大小调整控件大小
public void setControls(float newx,float newy,Control cons)
{
//遍历窗体中的控件,重新设置控件的值
foreach(Control con in cons.Controls)
{
//获取控件tag属性值,并分割后存储字符串数组
string[] mytag=con.Tag.ToString().Split(new char[]{':'});
float a = Convert.ToSingle(mytag[]) * newx;//根据窗体缩放比例确定控件的宽度值
con.Width = (int)a;
a = Convert.ToSingle(mytag[]) * newy;
con.Height = (int)a;//高度 a = Convert.ToSingle(mytag[]) * newx;
con.Left = (int)a;//左边缘距离
a = Convert.ToSingle(mytag[]) * newy;
con.Top = (int)a;//上边缘距离
Single currentSize = Convert.ToSingle(mytag[]) * newy;
con.Font = new Font(con.Font.Name,currentSize,con.Font.Style,con.Font.Unit);
if(con.Controls.Count>)
{
setControls(newx,newy,con);
} }
}
public void form_Resize(Form fr)
{
float newx = (fr.Width) / X;
float newy = (fr.Height) / Y;
setControls(newx, newy, fr);
fr.Text = fr.Width.ToString() + " " + fr.Height.ToString();
}
}
}

FormSetSelfAuto.cs

3、在窗体Form1中的调用方法

Form1的代码如下所示:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace Kaifafanli
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} FormSetSelfAuto fa = new FormSetSelfAuto();
private void Form1_Load(object sender, EventArgs e)
{
this.Resize += new EventHandler(Form1_Resize);
fa._x = this.Width;
fa._y = this.Height;
fa.setTag(this);
} private void Form1_Resize(object sender, EventArgs e)
{
fa.form_Resize(this);
}
}
}

Form1

上一篇:Tungsten Fabric+K8s轻松上手丨通过Kubernetes的服务进行基本应用程序连接


下一篇:关于java的Synchronized,你可能需要知道这些(下)