简体   繁体   中英

How to remove PictureBoxes dynamically?

I am trying to make pictureboxes fall continuously in the form. Here is the code that I tried.

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

I think it is better to delete the picture boxes which disappear from the form. How to do that?

You can remove it by removing the picturebox from form controls list.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM