如何在C#窗口应用程序中以编程方式创建按钮? [英] How can I create a button programmatically in C# window app?

查看:64
本文介绍了如何在C#窗口应用程序中以编程方式创建按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道拖放按钮很容易,但是一位讲师坚持要以编程方式创建按钮.

I know that it easy to just drag and drop a button, however a lecturer insists on creating buttons programmatically.

在Form1_Load方法中,我应该编写什么代码来创建一个简单的按钮?

In the Form1_Load method what code should I write to create a simple button?

 private void Form1_Load(object sender, System.EventArgs e)
 {

 }

这样在加载时按钮会显示出来吗?

So that on Load the button would show?

推荐答案

正如您所说的是Winforms一样,您可以执行以下操作...

As you said it is Winforms, you can do the following...

首先创建一个新的 Button 对象.

First create a new Button object.

Button newButton = new Button();

然后使用以下命令将其添加到该函数内的表单中:

Then add it to the form inside that function using:

this.Controls.Add(newButton);

您可以设置的其他属性...

Extra properties you can set...

newButton.Text = "Created Button";
newButton.Location = new Point(70,70);
newButton.Size = new Size(50, 100);

您遇到的问题是,您试图在Form_Load事件上进行设置,在那个阶段,该窗体尚不存在,并且您的按钮被覆盖了.您需要一个用于 Shown Activated 事件的委托才能显示该按钮.

Your issue you're running to is that you're trying to set it on Form_Load event, at that stage the form does not exist yet and your buttons are overwritten. You need a delegate for the Shown or Activated events in order to show the button.

例如,在您的 Form1 构造函数中,

For example inside your Form1 constructor,

public Form1()
{
    InitializeComponent();
    this.Shown += CreateButtonDelegate;
}

您的实际委托人是您创建按钮并将其添加到表单中的地方,类似的事情将起作用.

Your actual delegate is where you create your button and add it to the form, something like this will work.

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);
    newButton.Location = new Point(20, 50);
}

这篇关于如何在C#窗口应用程序中以编程方式创建按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆