为了删除您添加的最后一个按钮,您可以使用以下内容:
//a list where you save all the buttons created
List<Button> buttonsAdded = new List<Button>();
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
myText.Location = new Point(x2,y2);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
//add reference of the button to the list
buttonsAdded.Insert(0, myText);
}
//atach this to a button removing the other buttons
private void removingButton_Click(object sender, EventArgs e)
{
if (buttonsAdded.Count > 0)
{
Button buttonToRemove = buttonsAdded[0];
buttonsAdded.Remove(buttonToRemove);
this.Controls.Remove(buttonToRemove);
}
}
这应该允许您通过始终删除现有按钮中添加的最后一个按钮来删除任意数量的按钮。
更新
如果您希望能够将鼠标光标悬停在按钮上,然后使用Delete键将其删除,则可以使用以下解决方案:
- 设置
KeyPreview
为true,因此Form
可以接收在其控件中发生的关键事件
添加buttonsAdded
列表并button2_Click
按照此答案中描述的第一个解决方案进行修改
为您创建KeyDown
事件处理程序Form
并添加此代码:
private void MySampleForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
//get control hovered with mouse
Button buttonToRemove = (this.GetChildAtPoint(this.PointToClient(Cursor.Position)) as Button);
//if it's a Button, remove it from the form
if (buttonsAdded.Contains(buttonToRemove))
{
buttonsAdded.Remove(buttonToRemove);
this.Controls.Remove(buttonToRemove);
}
}
}