Kur*_*eri 0 c# button visual-studio winforms programmatically-created
我知道拖放按钮很容易,但是讲师坚持以编程方式创建按钮。
在 Form1_Load 方法中,我应该编写什么代码来创建一个简单的按钮?
private void Form1_Load(object sender, System.EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)
所以在加载按钮会显示?
正如您所说的是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);
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是您试图在 Form_Load 事件上设置它,在那个阶段表单还不存在并且您的按钮被覆盖。你需要一个代表Shown或Activated事件才能显示按钮。
例如在你的Form1构造函数中,
public Form1()
{
InitializeComponent();
this.Shown += CreateButtonDelegate;
}
Run Code Online (Sandbox Code Playgroud)
您的实际委托是您创建按钮并将其添加到表单的地方,类似这样的事情会起作用。
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16724 次 |
| 最近记录: |