【问题标题】:How to make picture box move across screen如何使图片框在屏幕上移动
【发布时间】:2020-04-04 20:52:55
【问题描述】:

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

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
    }

【问题讨论】:

  • picture是一个局部变量,把它变成一个field
  • 如果您的问题已得到解答,请记得接受答案

标签: c# winforms button timer picturebox


【解决方案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);
    }

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多