如何将事件添加到通过单击按钮动态创建的 PictureBox? (C#)

How can I add events to a PictureBox dynamically created by clicking button? (C#)

我通过单击表单中的按钮动态创建了一堆 PictureBox,但我不清楚如何向每个 PictureBox 添加事件。这是我的想法

private void insertarBloqueToolStripMenuItem_Click(object sender, EventArgs e)
{
    pbA = new PictureBox{
        Name = "picturebox" + contB,
        Image = new Bitmap(bloque),
        Size = pbA.Image.Size,
    };
    pbA.MouseDown += new MouseEventHandler(pbA_MouseDown);
    pbA.MouseUp += new MouseEventHandler(pbA_MouseUp);
    pbA.MouseMove += new MouseEventHandler(pbA_MouseMove);
    pbA.Paint += new PaintEventHandler(pbA_Paint);
    pbA.Cursor = Cursors.Hand;
    listaBloques.Add(pbA);
    panel1.Controls.Add(pbA);
}

这就是我得到的,你能帮我想想这个主意吗?我怎样才能创建一个单一的方法来移动列表中的一个 PictureBox?谢谢

你的想法很好! 但是这样写就足够了(但你的也可以):

pbA.Paint += pbA_Paint;// generally: ... += methodName;

而且您必须自己创建活动。例如:

void pbA_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    //do some cool stuff!
}

如果它被绘制在任何 PictureBoxes 上,那么将调用此方法。如果你想知道哪个 PictureBox 被绘制在上面,那么只需写:

void pbA_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    PictureBox picBox_active = sender as PictureBox;
    //do some cool stuff!
}

并且为了使一种方法仅移动一个 PictureBox,您可以将所需的对象作为参数:

void move(PictureBox picBox, int moveX, int moveY)
{
    picBox.Location = new Point(moveX, moveY);
}

您可以通过以下方式调用此方法:

PictureBox picBoxTest = new PictureBox();
move(picBoxTest, 5, 5);

为了更清楚地举个例子:

void pbA_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    PictureBox picBox_active = sender as PictureBox;
    move(picBox_active, 5, 5);
}

画完的PictureBox会移动到坐标5,5。