我的 C# winform 项目有问题。
在我的项目中,我有一个在运行时创建新按钮的函数。因为有时我制作了太多按钮,所以我想编写一个函数来删除我想在运行时删除的按钮。
有人可能已经有那个功能了吗?
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);
}
这就是我在运行时制作按钮的方式。
最佳答案
为了删除你添加的最后一个按钮,你可以使用这样的东西:
//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
,如本答案中描述的第一个解决方案为您的
Form
创建KeyDown
事件处理程序并在其中添加以下代码: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); } } }
关于c# - 如何删除按钮运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262178/