C# 控制生成的picturebox
我正在尝试制作一个用c#编码的小游戏,这个游戏涉及移动敌人。 这些敌人是使用以下代码繁殖的,此代码多次用于繁殖多个敌人C# 控制生成的picturebox,c#,winforms,C#,Winforms,我正在尝试制作一个用c#编码的小游戏,这个游戏涉及移动敌人。 这些敌人是使用以下代码繁殖的,此代码多次用于繁殖多个敌人 private void EventHandler(Action<object, EventArgs> spawnBox) { Random randomPlek = new Random(); int xPlek; xPlek = randomPlek.Next(1000, 1100
private void EventHandler(Action<object, EventArgs> spawnBox)
{
Random randomPlek = new Random();
int xPlek;
xPlek = randomPlek.Next(1000, 1100);
int yPlek;
yPlek = (randomPlek.Next(0, 8)) * 100;
var picture = new PictureBox
{
Name = "pictureBoxLM",
Size = new Size(150, 100),
SizeMode = PictureBoxSizeMode.StretchImage,
BackColor = Color.Transparent,
Location = new Point(xPlek, yPlek),
Image = Leeuwenmier,
};
this.Controls.Add(picture);
}
如何在代码中调用生成的picturebox而不出错?WinForms控件有名称,但这并不意味着您可以使用该名称作为C#标识符来访问它们 PictureBox在
EventHandler()
中只有一个命名引用,即picture
,但一旦控件离开该方法,该引用将超出范围
您需要再次找到控件,或者找到其他方法来引用生成的控件
因此,要么:
var allPictureBoxes = this.Controls.Find("PictureBoxLM");
foreach (var pictureBox in allPictureBoxes)
{
// ...
}
或者把这个写在你的表格上:
List<PictureBox> pictureBoxList = new List<PictureBox>();
在此之后,您可以使用此选项进行碰撞检测:
foreach (var pictureBox in pictureBoxList)
{
// ...
}
this.Controls.Add(picture);
pictureBoxList.Add(picture);
foreach (var pictureBox in pictureBoxList)
{
// ...
}