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

时间:2019-12-11 14:32:24

标签: c# winforms button timer picturebox

我正在尝试使我的图片框在屏幕上移动,但出现此错误:计时器内的当前上下文中不存在“图片”。我该怎么办?

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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

好吧,picture局部变量,因此在Button1_Click之外不可见。让我们把它变成一个 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); 
}