C#实现控件与窗体大小自适应
昨天,做RFID项目的时候,需要使得窗体中控件按照窗体大小来调整,从而达到视觉上的自适应效果。我的窗体大小是按照1024*768的分辨率来设置的,按照项目的要求窗体需要最大化显示,这时问题就出现了,控件大小及字体都按照原来的设置显示,窗体中就出现了空白的地方,而且有的控件错位显示。
我试着设置了控件的Dock与Anchor属性,但都无济于事,最后只能来循环设置控件的大小,从而使得布局美观。网上找了相关资料,最后自己整理写出了如下代码。
首先,在Form窗体中添加如下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | private void setTag(Control cons) { //MessageBox.Show("setTag"); foreach (Control con in cons.Controls) { con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size; if (con.Controls.Count > 0) { //MessageBox.Show("ok"); setTag(con); } } } //调整每个控件的大小 private void setControls(float newx, float newy, Control cons) { foreach (Control con in cons.Controls) { //MessageBox.Show(con.Tag.ToString()); string[] mytag = con.Tag.ToString().Split(':'); 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 currentSize = Convert.ToSingle(mytag[4]) * newy; con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) { setControls(newx, newy, con); } } } //窗体大小自适应 private void NewOrderDashForm_Resize(object sender, EventArgs e) { //MessageBox.Show("resize"); // throw new Exception("The method or operation is not implemented."); float newx = (this.Width) / X; float newy = this.Height / Y; setControls(newx, newy, this); this.Text = this.Width.ToString() + " " + this.Height.ToString(); } |
添加Form_load事件,代码如下
1 2 3 4 5 | //窗体与控件的自适应 this.Resize += new EventHandler(NewOrderDashForm_Resize); X = this.Width; Y = this.Height; setTag(this); |
最后,别忘了声明变量X,Y,这样就可以实现控件大小与窗体的自适应了,也解决了我的一大问题,嘿嘿。