c#在单击时获取以编程方式添加的按钮的位置

c# Get Location of programmatically added Button on Click

我在不同的位置动态创建了很多按钮,每个按钮都应该响应同一个事件。因为我必须知道我点击了哪个按钮,所以我需要我点击的按钮的位置。我不能为每个按钮添加不同的 EventHandler,它们在 30*50 的网格上生成,这意味着在最坏的情况下我会得到 1500 个按钮。按钮太多了。

    private void createNewEnt(int ID, Point position, int style)
    {
        Button b = new Button();
        b.Location = getItemGridLoc(position);
        b.Text = getInitial(ID);
        b.Size = new System.Drawing.Size(21, 21);
        b.FlatStyle = FlatStyle.Popup;
        b.Click += new EventHandler(bClick);
        if (style == 0)
        {
            b.BackColor = Color.White;
            b.ForeColor = Color.Black;
        }
        else if (style == 1)
        {
            b.BackColor = Color.Black;
            b.ForeColor = Color.White;
        }
        this.Controls.Add(b);
        b.BringToFront();
    }

    void bClick(object sender, EventArgs e)
    {
        MessageBox.Show("you clicked on a Button :D");
    }

您可以使用事件处理程序的 sender 参数并将其转换为按钮,然后检索其位置。

void bClick(object sender, EventArgs e)
{
    Button cb = (sender as Button);
    MessageBox.Show("You clicked on a Button :D!");
    MessageBox.Show(String.Format("Location of clicked Button : {0}, {1}.", cb.Location.X, cb.Location.Y)); // This is just for example.
}

同样,您还可以使用按钮做其他事情,即 cb and/or 获取它的其他属性。

void bClick(object sender, EventArgs e)
{
    Button btn1 = (Button)sender;
    string buttonID = btn1.ID;
    MessageBox.Show("you clicked on a Button :D");
}

这是获取按钮 ID 和所有其他 属性 所需的方法。