在 Form1_Load 方法中我应该编写什么代码来创建一个简单的按钮?
private void Form1_Load(object sender, System.EventArgs e)
{
}
这样在加载时就会显示按钮。
正如你所说,它是Winforms,你可以执行以下操作...
首先创建一个新的
Button
对象。
Button newButton = new Button();
然后使用以下方法将其添加到该函数内的表单中:
this.Controls.Add(newButton);
您可以设置的额外属性...
newButton.Text = "Created Button";
newButton.Location = new Point(70, 70);
newButton.Size = new Size(50, 100);
您遇到的问题是您尝试在 Form_Load 事件上设置它,在该阶段表单尚不存在并且您的按钮被覆盖。您需要
Shown
或 Activated
事件的委托才能显示按钮。
例如在您的
Form1
构造函数中,
public Form1()
{
InitializeComponent();
this.Shown += CreateButtonDelegate;
}
您的实际委托是您创建按钮并将其添加到表单中的地方,类似这样的事情就可以了。
private void CreateButtonDelegate(object sender, EventArgs e)
{
Button newButton = new Button();
this.Controls.Add(newButton);
newButton.Text = "Created Button";
newButton.Location = new Point(70, 70);
newButton.Size = new Size(50, 100);
}
在您的事件加载表单上输入此代码
private void Form1_Load(object sender, EventArgs e)
{
Button testbutton = new Button();
testbutton.Text = "button1";
testbutton.Location = new Point(70, 70);
testbutton.Size = new Size(100, 100);
testbutton.Visible = true;
testbutton.BringToFront();
this.Controls.Add(testbutton);
}
很简单:
private void Form1_Load(object sender, System.EventArgs e)
{
Button btn1 = new Button();
this.Controls.add(btn1);
btn1.Top=100;
btn1.Left=100;
btn1.Text="My Button";
}