我想創建一個按鈕,創建其它按鈕,我希望它能夠創建像無限按鈕在螢屏上我試著
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);
我相信它確實添加了它但它沒有顯示所以我如何將按鈕添加到螢屏上
uj5u.com熱心網友回復:
我認為這是因為您將所有新按鈕放在同一位置。另外,取下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.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344729.html
