Как заставить изображение перемещаться по экрану - PullRequest
0 голосов
/ 11 декабря 2019

Я пытаюсь заставить мою картинку-коробку перемещаться по экрану, но у меня есть эта ошибка: «картинка» не существует в текущем контексте внутри таймера. Что я могу сделать?

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
    }

Ответы [ 2 ]

1 голос
/ 11 декабря 2019

Ну, picture является локальной переменной и, таким образом, не виден снаружи Button1_Click. Давайте превратим его в поле :

 // 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); 
}
1 голос
/ 11 декабря 2019

Попробуйте поместить изображение за пределы кнопки, кликните вот так:

PictureBox picture;
private void Button1_Click(object sender, EventArgs e)
    {
        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;
        if(picture != null)
            picture.Location = new System.Drawing.Point(x, y);
    }
...