控件大小和字体随窗体大小变化

来源:互联网 发布:网络用语老板什么意思 编辑:程序博客网 时间:2024/05/18 02:14

为了避免窗体大小发生变化时控件布局出现尴尬的局面,你可能要设置控件的Anchor或者Dock属性,诶,不过这很头疼的,界面复杂时不好控制。还有另一种方法,布局控件,可是它也不是万能的了,怎么办呢?哈哈,别急,下面给你好的方法:

 

        //记录控件的宽、高、控件左边缘与其所在容器左边缘间距、控件上边缘与其所在容器上边缘间距、控件的字体大小

        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);

                }

            }

        }

 

        private void Form1_Resize(object sender, EventArgs e)

        {

            float newx = this.Width / X;

            float newy = this.Height / Y;

            //float newy = (this.Height - this.statusStrip1.Height) / (Y - y);

            setControls(newx, newy, this);

        }

 

        float X=1, Y=1;

        //float y = 0;

        private void Form1_Load(object sender, EventArgs e)

        {

            X = this.Width;

            Y = this.Height;

            //y = this.statusStrip1.Height;

            setTag(this);

        }

 

OK,搞定了O(_)O~

原创粉丝点击