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

本文介绍了一种方法,当窗体大小改变时,通过记录并调整控件的尺寸、位置和字体大小,确保它们能按比例自动适应窗体的变化。主要涉及控件的Tag属性、控件的尺寸计算以及窗体Resize事件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了避免窗体大小发生变化时控件布局出现尴尬的局面,你可能要设置控件的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~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值