winform 宽度设置百分比

在WinForms中,设置控件的宽度为百分比需要在窗体的Resize事件中重新计算控件的宽度。以下是一个简单的例子,展示了如何设置一个Button的宽度为窗体宽度的50%,设置另一个按钮的宽度为窗体宽度的25%。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace width1
{
    public partial class MainForm2 : Form
    {
        private Button button1;
        private Button button2;
        public MainForm2()
        {
            button1=new Button();
            button1.Text = "button1";
            button1.Width = (int)(this.ClientSize.Width * 0.5);

            button2= new Button();
            button2.Text = "button2";
            button2.Location = new System.Drawing.Point(50, 50);
            button2.Width = (int)(this.ClientSize.Width * 0.25);

            this.Resize += MainForm_Resize;

            this.Controls.Add(button1);
            this.Controls.Add(button2);
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            // 假设你有一个名为button1的按钮
            button1.Width = (int)(this.ClientSize.Width * 0.5); // 设置宽度为窗体宽度的50%
            button2.Width = (int)(this.ClientSize.Width * 0.25);

        }
    }
}

窗体拉伸时会触发Resize事件,从而调用MainForm_Resize方法。MainForm_Resize方法会改变button1和button2的宽度为窗口新宽度的50%和25%。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值