Move picturebox made in a class

时间:2017-05-16 09:22:59

标签: c# winforms

I've made a picturebox.

public void create(Form1 u, int number, int x, int y)
{
    pictureBox1 = new PictureBox();
    pictureBox1.Location = new Point(x, y);
    pictureBox1.Name = "invader" + number;
    pictureBox1.Size = new Size(60, 54);
    pictureBox1.Image = Image.FromFile("../sprite.jpg");
    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
    u.Controls.Add(pictureBox1);
}

How do I move this by like 1 pixel every 20 milliseconds? I got a timer and I've tried a few things but I do not know how to properly select the picture box that this class had made so I can move it (it all has to be written within this class) I want the box to move down. The X coordinate should stay the same.

private void timer1_Tick(object sender, EventArgs e)
{

}

My super exciting timer code. It is located in the main form code.

1 个答案:

答案 0 :(得分:2)

您已动态创建PictureBox,并且使用的变量是局部变量,因此在退出创建代码后,您不再直接引用所创建的图片框。
但是,您仍然可以从 u

形式的控件集合中提取图片框。
private void timer1_Tick(object sender, EventArgs e)
{ 
    PictureBox pic = u.Controls.OfType<PictureBox>().FirstOrDefault(x => x.Name = "invader" + currentPicNumber;
    if(pic != null) pic.Location = new Point(pic.Location.X, pic.Location.Y + 1);
}

现在我们应该解决两个问题 currentPicnumber 的值是什么,您应该引用已添加PictureBox的Form1 u 的实例。

这些问题可以通过引用Form1的类级变量(我假设您已经有此引用)和另一个保存您要移动的当前图片框的数量的变量来解决。

相反,如果您需要移动多个动态添加的PictureBox,您可以提取所有名称以“入侵者”文本开头的图片框并将其循环

private void timer1_Tick(object sender, EventArgs e)
{ 
    var picList = u.Controls.OfType<PictureBox>().FirstOrDefault(x => x.Name.StartsWith("invader");
    foreach(PictureBox pic in picList)
        pic.Location = new Point(pic.Location.X, pic.Location.Y + 1);
}
相关问题