如何动态删除PictureBoxes?

时间:2015-02-21 06:22:30

标签: c# picturebox

我试图让图片盒不断下降。 这是我试过的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Rain_dropz
{
    public partial class Form1 : Form
    {
        PictureBox[] RD = new PictureBox[500];
        int ndrop = 0;
        public Form1()
        {
            InitializeComponent();
        }

        public void dropIt()
        {
            for (int i = 0; i < ndrop; i++)
            {
                RD[i].Top += 10;
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Random rnd = new Random();
            int l = rnd.Next(1,545);
            RD[ndrop] = new PictureBox();
            RD[ndrop].BackColor = System.Drawing.Color.MediumBlue;
            RD[ndrop].Size = new Size(5, 5);
            RD[ndrop].Location = new Point(l, 0);
            this.Controls.Add(RD[ndrop]);
            ndrop++;
            dropIt();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Start();
        }
    }
}

我认为最好删除从表单中消失的图片框。怎么做?

1 个答案:

答案 0 :(得分:1)

您可以通过从表单控件列表中删除图片框来删除它。

private void timer1_Tick(object sender, EventArgs e)
    {
        Random rnd = new Random();
        int l = rnd.Next(1,545);
        RD[ndrop] = new PictureBox();
        RD[ndrop].BackColor = System.Drawing.Color.MediumBlue;
        RD[ndrop].Size = new Size(5, 5);
        RD[ndrop].Location = new Point(l, 0);
        RD[ndrop].LocationChanged += pb_LocationChanged;
        this.Controls.Add(RD[ndrop]);
        ndrop++;
        dropIt();
    }


void pb_LocationChanged(object sender, EventArgs e)
    {
        // FORM_LASTBOUND is the Y-Axis point after which you wanted to remove the picturebox.
        if ((sender as PictureBox).Top > FORM_LASTBOUND)
        {
            this.Controls.Remove(sender as PictureBox);
        }

    }
相关问题