【C#】窗體控制元件隨窗體大小改變(包括字型大小)
阿新 • • 發佈:2019-02-12
其實Anchor和Dock屬性也可以實現,但好象只對容器效果理想,而且字型大小也沒有變化.最近論壇上有好多這樣的貼子,具體實現程式碼如下:
然後在你窗體的建構函式InitializeComponent();下面新增:private 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); } } private void setControls(float newx, float newy, Control cons) { foreach (Control con in cons .Controls ) { string[] 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 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 ); } } } void Form1_Resize(object sender, EventArgs e) { // throw new Exception("The method or operation is not implemented."); float newx = (this.Width )/ X; // float newy = (this.Height - this.statusStrip1.Height) / (Y - y); float newy = this.Height / Y; setControls(newx, newy, this); //this.Text = this.Width.ToString() +" "+ this.Height.ToString(); }
this.Resize += new EventHandler(Form1_Resize);
X = this.Width;
Y = this.Height;
y = this.statusStrip1.Height;
setTag (this);
當然定義了兩個全域性變數,private float X; private float Y;
細心的你一定會發現還有個y ;這是因為如果有statusStrip1之類的控制元件,這是就一定要注意,窗體的實際寬度和高度一定要減去statusStrip1之類.
如果是容器,最好將Anchor和Dock屬性也修改過來.
效果還不錯.
原帖地址:http://blog.csdn.net/baihe_591/article/details/2495097