C#从Struct获取图片框

问题描述 投票:0回答:1

我想获得在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++)
            {

            }
        }

这件事就好了。但它只是创造了图片盒。因为循环是空的,因为我无法弄清楚要做什么。我只是想做那样的事,

picture + obstacle_numb.Location = new Point(x,y); (我需要这张照片+ obstacle_numb组合。)

但也知道这是不可能的。 foreach出现在我的脑海里,但我不知道如何使用它。也许这样的东西可以修复。

foreach(PictureBox objects from picture) //It doesn't work too.

我现在卡住了,等待你的帮助。提前致谢。

c# struct picturebox
1个回答
1
投票

最简单的方法是迭代所有类型为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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.