C# 从结构中获取图片框
C# Getting pictureboxes from Struct
我想获取在结构中创建的对象。不过,显示代码会更好地解释它。
private void Obstacle()
{
obstacle_pos_x = obstacle_random_x.Next(1000);
obstacle_pos_y = obstacle_random_y.Next(700);
picture = new PictureBox
{
Name = "pictureBox" + obstacle_numb,
Size = new Size(32, 32),
Location = new Point(obstacle_pos_x,obstacle_pos_y),
BackColor = Color.Black,
};
this.Controls.Add(picture);
}
这是 Obstacle 方法内部的结构。如您所见,此方法创建了图片框,我想将它们拉入 KeyPressEvents。比如,如果我按 W,所有由 struct 创建的图片框都必须移动 -10(y 轴)。
else if (e.KeyCode == Keys.W)
{
y -= chrspeed;
obstacle_numb++;
Obstacle();
for (int i = 0; i <= obstacle_numb; i++)
{
}
}
好吧,这次活动。但它只是创建图片框。 For 循环是空的,因为我不知道该怎么做。我只是想做那样的事情,
图片+obstacle_numb.Location = new Point(x,y); (我需要这张图片+obstacle_numb组合。)
但也知道这是不可能的。我想到了foreach,但我不知道如何使用它。如果修复,也许这样的东西可以工作。
foreach(PictureBox objects from picture) //It doesn't work too.
我现在被卡住了,等待你的帮助。提前致谢。
最简单的方法是迭代 PictureBox 类型的所有子控件:
...
foreach (var pict in this.Controls.OfType<PictureBox>())
{
// pict is now a Picturebox, you can access all its properties as you have constructed it
// the name was constructed that way: Name = "pictureBox" + obstacle_numb,
if (pict.Name != "pictureBox1")
{
pict.Location = new Point(pict.X, pict.Y-10);
}
}
我想获取在结构中创建的对象。不过,显示代码会更好地解释它。
private void Obstacle()
{
obstacle_pos_x = obstacle_random_x.Next(1000);
obstacle_pos_y = obstacle_random_y.Next(700);
picture = new PictureBox
{
Name = "pictureBox" + obstacle_numb,
Size = new Size(32, 32),
Location = new Point(obstacle_pos_x,obstacle_pos_y),
BackColor = Color.Black,
};
this.Controls.Add(picture);
}
这是 Obstacle 方法内部的结构。如您所见,此方法创建了图片框,我想将它们拉入 KeyPressEvents。比如,如果我按 W,所有由 struct 创建的图片框都必须移动 -10(y 轴)。
else if (e.KeyCode == Keys.W)
{
y -= chrspeed;
obstacle_numb++;
Obstacle();
for (int i = 0; i <= obstacle_numb; i++)
{
}
}
好吧,这次活动。但它只是创建图片框。 For 循环是空的,因为我不知道该怎么做。我只是想做那样的事情,
图片+obstacle_numb.Location = new Point(x,y); (我需要这张图片+obstacle_numb组合。)
但也知道这是不可能的。我想到了foreach,但我不知道如何使用它。如果修复,也许这样的东西可以工作。
foreach(PictureBox objects from picture) //It doesn't work too.
我现在被卡住了,等待你的帮助。提前致谢。
最简单的方法是迭代 PictureBox 类型的所有子控件:
...
foreach (var pict in this.Controls.OfType<PictureBox>())
{
// pict is now a Picturebox, you can access all its properties as you have constructed it
// the name was constructed that way: Name = "pictureBox" + obstacle_numb,
if (pict.Name != "pictureBox1")
{
pict.Location = new Point(pict.X, pict.Y-10);
}
}