将图片框添加到上一个

时间:2017-03-04 13:16:33

标签: c# visual-studio

你好我在使用c#工作。我正在尝试制作的算法会在点击按钮时添加一个已经存在于前一个图片框中的随机图片框。但我不知道如何制作它。我的意思是我在屏幕上有例如PictureBox1,当我点击按钮时,第二个PictureBox应该转到pictureBox1.Top - 90,因为图片框是90x90,当再次点击按钮时,第三个按钮在第二个顶部...

我现在拥有的东西,当我点击按钮时,每次都会将新的图片框添加到第一个PictureBox1的前90位:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public static Random rand = new Random();  

    private void button1_Click_1(object sender, EventArgs e)
    {
        int box = rand.Next(1, 4);
        if (box == 1)
        { pictureBox2.Top = pictureBox1.Top - 90; }
        if (box == 2)
        { pictureBox3.Top = pictureBox1.Top - 90; }
        if (box == 3)
        { pictureBox4.Top = pictureBox1.Top - 90; }


    }

}

1 个答案:

答案 0 :(得分:1)

试试这个:

PictureBox _lastAddedPictureBox;
List<int> _notAddedBoxes = new List<int> {1,2,3};

private void button1_Click_1(object sender, EventArgs e)
{
    if(_lastAddedPictureBox == null)
    { 
      // if we assumed that pictureBox1 has been already added to the right location.
      _lastAddedPictureBox = pictureBox1;
    }

     int index = rand.Next(0, _notAddedBoxes.Count - 1);
     int box = _notAddedBoxes[index];

    if (box == 1)
    {
       pictureBox2.Top = _lastAddedPictureBox.Top - 90; 
       _lastAddedPictureBox  =  pictureBox2;
    }
    if (box == 2)
    { 
       pictureBox3.Top = _lastAddedPictureBox.Top - 90; 
      _lastAddedPictureBox  =  pictureBox3;
    }
    if (box == 3)
    { 
       pictureBox4.Top = _lastAddedPictureBox.Top - 90; 
       _lastAddedPictureBox  =  pictureBox4;
    } 

    // if we assume that you don't want to keep moving what has been already added.
    _notAddedBoxes.RemoveAt(index);
}