在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%。