如何让图片框在屏幕上移动

How to make picture box move across screen

我试图让我的图片框在屏幕上移动,但出现此错误:'picture' 在计时器的当前上下文中不存在。我能做什么?

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
    }

尝试将图片放在按钮点击之外,如下所示:

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

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