0
votes

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
Where is the timer code? - Steve
added the timer code - Chaoss1848
just set the position in the tick ? I also recommend using System.Timers.Timer it offers an Elapsed event for the defined Interval. - Felix D.
I know how to change the position and all. but i dont know how to target the picturebox that I made specifically. I tried just doing pictureBox1.Top or .Location etc but none of that worked. - Chaoss1848
@Chaoss1848 ... I tried just doing pictureBox1.Top or .Location etc ... that's good. Can you show us your attempt with Location? - default locale

1 Answers

2
votes

You have created the PictureBox dynamically and the variable used is a local variable, so after exiting the creation code you have no more a direct reference to the picturebox created.
However you have still the possibility to extract the picturebox from the controls collection of the form 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);
}

Now we should resolve two problems.
What value for currentPicnumber and you should have a reference to the instance of Form1 u where you have added the PictureBox.

These problems could be solved with a class level variable with the reference to the Form1 (I suppose that you have already this reference) and another variable that keeps the number of the current picturebox that you want to move.

Instead if you need to move more than one PictureBox added dynamically you could extract all the pictureboxes that whose name start with the "invader" text and loop over them

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);
}