在时间后删除PictureBox

问题描述 投票:1回答:2

我正在做一个简单的游戏,我需要在一段时间后删除图片而不冻结其他所有内容。我正在爆炸事件:

private void Explode(int x, int y)
{
  PictureBox explosion = new PictureBox();
  explosion.Image = Properties.Resources.explosion;
  explosion.SizeMode = PictureBoxSizeMode.StretchImage;
  explosion.Size = new Size(50, 50);
  explosion.Tag = "explosion";
  explosion.Left = x;
  explosion.Top = y;            
  this.Controls.Add(explosion);
  explosion.BringToFront();
}

我已经有一个运行该游戏的计时器,并且我想使用if语句在持续3秒钟时删除图片。

private void timer1_Tick(object sender, EventArgs e)
{
  foreach (Control x in this.Controls) 
  {
    if (x is PictureBox && x.Tag == "explosion")
    {
      if (EXPLOSION LASTS MORE THEN 3sec)
      {
        this.Controls.Remove(x);
      }
    }
  }
}

我该怎么做?

c# .net winforms timer picturebox
2个回答
1
投票

假设您可能同时有多个图片框,那么可以对像框使用不同的爆炸定时,而不必对多个图片框使用单个计时器,可以使用async / await和Task.Delay,如下所示:

private async void button1_Click(object sender, EventArgs e)
{
    await AddExplodablePictureBox();
}
private async Task AddExplodablePictureBox()
{
    var p = new PictureBox();
    p.BackColor = Color.Red;
    //Set the Image and other properties
    this.Controls.Add(p);
    await Task.Delay(3000);
    p.Dispose();
}

0
投票

删除图片框之前,当然需要释放图片框资源。

但是释放时有问题。有关更多信息,您可以从下面的链接阅读更多。

c# picturebox memory releasing problem

© www.soinside.com 2019 - 2024. All rights reserved.