2015-02-21 3 views
1

Я пытаюсь сделать pictureboxes непрерывно падать в форме. Вот код, который я пробовал.Как удалить PictureBoxes динамически?

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

Вы можете удалить его, удалив изображение из списка управления формами.

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

    } 
Смежные вопросы