我如何才能知道表格中是否有对象?

时间:2015-05-31 03:43:02

标签: c#

我想在随机位置添加许多按钮到表单(C#),但我不是从这些按钮重叠,所以问题是我可以知道点是空的还是已经存在对象?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

    private Random R = new Random();
    private List<Button> Buttons = new List<Button>();

    private void button1_Click(object sender, EventArgs e)
    {
        while (Buttons.Count > 0)
        {
            Buttons[0].Dispose();
            Buttons.RemoveAt(0);
        }

        bool overlapping;
        for(int i = 1; i <= 10; i++)
        {
            Button btn = new Button();
            btn.Text = i.ToString();
            this.Controls.Add(btn);
            do
            {
                overlapping = false;
                btn.Location = new Point(R.Next(this.ClientSize.Width - btn.Width), R.Next(this.ClientSize.Height - btn.Height));
                foreach(Button otherBtn in Buttons)
                {
                    if (btn.Bounds.IntersectsWith(otherBtn.Bounds))
                    {
                        overlapping = true;
                        break;
                    }
                }
            } while (overlapping);
            Buttons.Add(btn);
        }
    }

}