【问题标题】:how to create a button that creates another button and show up immediately如何创建一个按钮来创建另一个按钮并立即显示
【发布时间】:2023-03-24 20:14:02
【问题描述】:

我想创建一个按钮来创建其他按钮,并且我希望它能够在屏幕上创建无限按钮 我试过了

Button button = new Button();
button.Location = new Point(100,100);
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();
this.Controls.Add(button);

我相信它确实添加了它,但它没有显示出来 那么如何将按钮添加到屏幕上

【问题讨论】:

  • Application.Restart(); ???

标签: c# visual-studio winforms button


【解决方案1】:

我认为这是因为您将所有新按钮都放在同一个位置。另外,删除Application.Restart() 部分。

Button button = new Button();
button.Location = new Point(100,100); //change this to random or something 
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();//don't restart the application everytime you click!
this.Controls.Add(button);

您还应该订阅新按钮的 OnClick 事件。您应该创建一个包含上述所有代码的本地函数并订阅新按钮。这样您就可以递归地添加按钮。假设原始按钮的名称是button1,则将其单击方法更改为:

private void button1_Click(object sender, EventArgs e)
{
    Random random = new Random(System.Environment.TickCount);//random location everytime
    Button button = new Button();
    button.Text = "IT Woreked";
    button.Size = new Size(26, 26);// the size might be a bit small. You might want to increase it.
    button.Location = new Point(random.Next(0, this.Size.Width - button.Width), random.Next(0, this.Size.Height - button.Height)); //change this to random or something 
    button.Visible = true;
    this.Controls.Add(button);
    button.Click += button1_Click;//when the new button is clicked, call this method.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多