如何删除按钮运行时间

如何删除按钮运行时间

本文介绍了如何删除按钮运行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#winform项目中遇到问题。

在我的项目中,我具有在运行时创建新按钮的功能。因为有时我制作了太多的按钮,所以我想编写一个函数来删除要在运行时删除的按钮。
有人可能已经具有该功能?

I have a problem in my C# winform project.
In my project I have function that make a new button at runtime. Because sometimes I make too many buttons I want to write a function that deletes the button that I want to delete at run time.Someone maybe have already that function?

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);
}

这就是我在运行时制作按钮的方式。

that is how I make the button at runtime.

推荐答案

要删除已添加的最后一个按钮,可以使用以下命令:

In order to remove the last button you've added, you can use something like this:

//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);
    }
}

这应允许您删除尽可能多的按钮想要通过始终删除现有添加的最后一个添加来删除。

This should allow you to remove as many buttons as you want by removing always the last one added from the existing ones.

更新

如果您希望能够使用鼠标光标悬停一个按钮,然后使用 Delete 键将其删除,则可以使用以下解决方案:

If you want to be able to hover a button with your mouse cursor and then delete it with Delete key, you can use this solution:


  • KeyPreview 设置为 true ,这样 Form 可以接收按键事件在其控件中发生

  • 添加 button☎列表并修改 button2_Click 如此答案中所述的第一个解决方案

  • set KeyPreview to true, so Form can receive key events occured in its controls
  • add buttonsAdded list and modify button2_Click as in the first solution described in this answer

为您的<$创建 KeyDown 事件处理程序c $ c> Form 并添加以下代码:

create KeyDown event handler for your Form and add this code ot it:

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);
            }
    }
}


这篇关于如何删除按钮运行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:48