Search code examples
c#winformsbuttontimerpicturebox

How to make picture box move across screen


I am trying to make my picturebox move across the screen but I have this error: 'picture' does not exist in the current context inside the timer. What can I do?

private void Button1_Click(object sender, EventArgs e)
    {
        var picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(20, 20),
            Location = new System.Drawing.Point(x, y),
            Image = image1,

        };
        this.Controls.Add(picture);
        timer1.Enabled = true;

    }
    private void Timer1_Tick(object sender, EventArgs e)
    {
        //redefine pictureBox position.
        x = x - 50;
        picture.Location = new System.Drawing.Point(x, y); //'picture' does not exist in the current context
    }

Solution

  • Well, picture is a local variable and thus is not visible outside Button1_Click. Let's turn it into a field:

     // now picture is a private field, visible within th class
     //TODO: do not forget to Dispose it
     private PictureBox picture;
    
     private void Button1_Click(object sender, EventArgs e)
     {
        if (picture != null) // already created
          return;
    
        picture = new PictureBox
        {
            Name     = "pictureBox",
            Size     = new Size(20, 20),
            Location = new System.Drawing.Point(x, y),
            Image    = image1,
            Parent   = this, // instead of this.Controls.Add(picture);
        };
    
        timer1.Enabled = true;
    }
    
    private void Timer1_Tick(object sender, EventArgs e)
    {
        //redefine pictureBox position.
        x = x - 50;
    
        if (picture != null) // if created, move it
          picture.Location = new System.Drawing.Point(x, y); 
    }