我通过单击表单中的按钮动态创建一堆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?谢谢
答案 0 :(得分:0)
你的想法非常好! 但它应该写(但你的工作也很好):
pbA.Paint += pbA_Paint;// generally: ... += methodName;
你必须创建它自己的事件。例如:
void pbA_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
//do some cool stuff!
}
如果它被绘制在PictureBox的任何上,那么将调用此方法。如果您想知道哪个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。