热门搜索 :
考研考公
您的当前位置:首页正文

winform窗体和控件自适应

来源:伴沃教育


有时winform窗体的大小会改变,此时窗体上的控件会很混乱,如何可以使控件自适应窗体呢?以

下就是方法:

1、首先在自己的命名空间里先建一个Autosize.cs类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace 自己的命名空间

{

class Autosize

{

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 > 0) setTag(con);

}

}

string[] mytag;

public void setControls(float newx, float newy, Control cons)

{

foreach (Control con in cons.Controls)

{

if (con.Tag != null)

{

mytag = con.Tag.ToString().Split(new char[] { ':' });

float a = Convert.ToSingle(mytag[0]) * newx; con.Width = (int)a;

a = Convert.ToSingle(mytag[1]) * newy; con.Height = (int)(a);

a = Convert.ToSingle(mytag[2]) * newx;

con.Left = (int)(a);

a = Convert.ToSingle(mytag[3]) * newy; con.Top = (int)(a);

Single Math.Min(newx,

currentSize = Convert.ToSingle(mytag[4]) *

newy);

}

//con.Font = new Font

(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);

con.Font = new Font

(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);

if (con.Controls.Count > 0)

{

setControls(newx, newy, con);

}

}

}

}

}

2、在别的窗体中调用此类中的方法可实现winform窗体自适应

例: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;

using Semi_auto_CLIA.ProQuery;

using Semi_auto_CLIA.LabTest;

namespace 自己的命名空间

{

public partial class frmMain: Form

{

Autosize autosize = new Autosize();

private float X ;//宽í度è

private float Y;//高?度è

public frmMain()

{

InitializeComponent();

X = this.Width;

Y = this.Height;

autosize.setTag(this);

//this.skinEngine1.SkinFile = \"EmeraldColor1.ssk\";

}

private void frmMain_SizeChanged(object sender, EventArgs e)

{

float newx = (this.Width) / X;

float newy = this.Height / Y;

autosize.setControls(newx, newy, this);

}

}

}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top