winform控件只适应窗口大小

本文介绍了一种在Windows窗体应用程序中实现控件自适应布局的方法。通过在窗口加载及大小变化时,根据窗口的原始尺寸和当前尺寸,等比例调整放置在Panel容器内的控件的位置和大小。

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

要实现这个功能,选择使用代码,当窗口缩放的时候,控件位置与大小也跟着等比例缩放。将控件存放在Pannl容器中,以方便获取控件。

namespace 控件布局的自适应
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //容器的宽高
        public int normWidth, normHeight;
        //用来存放需要改变大小的控件字典
        public Dictionary<string, Rec> buttonControl = new Dictionary<string, Rec>();//
        //写一个类,里面用来存放控件原始的位置和宽高
        public class Rec
        {
            public int x;
            public int y;
            public int width;
            public int height;
           public Rec(int x,int y, int width,int height)
           {
                this.x = x;
                this.y = y;
                this.height = height;
                this.width = width;

           }
        }
        //窗口加载时触发的事件
        private void Form1_Load(object sender, EventArgs e)
        {
            //将初始值保存
            normWidth = this.panel2.Width;
            normHeight = this.panel2.Height;
            //遍历容器中的所有控件,添加进字典
            foreach (Control item in this.panel2.Controls)
            {
                buttonControl.Add(item.Name, new Rec(item.Left, item.Top, item.Width,item.Height));
            }
        }

        //窗口大小变换时触发的事件
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //获取改变窗口位置后的容器宽高
            int w = panel2.Width;
            int h = panel2.Height;
            //根据缩放后的容器大小按比例重新给控件位置赋值
            foreach (Control item in panel2.Controls)//遍历容器中的控件
            {
                item.Left =(int)(w * 1.0 / normWidth * buttonControl[item.Name].x);
                item.Top = (int)(h * 1.0 / normHeight * buttonControl[item.Name].y);
                item.Width = (int)(w * 1.0 / normWidth * buttonControl[item.Name].width);
                item.Height = (int)(h * 1.0 / normHeight * buttonControl[item.Name].height);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猪猪派对

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值