如何创建一个创建另一个按钮并立即显示的按钮
how to create a button that creates another button and show up immediately
我想创建一个可以创建其他按钮的按钮,我希望它能够在屏幕上创建类似无限按钮的按钮
我试过了
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()
部分。
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.
}
我想创建一个可以创建其他按钮的按钮,我希望它能够在屏幕上创建类似无限按钮的按钮 我试过了
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()
部分。
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.
}