简体   繁体   中英

How can I know point in form have object or not?

我想在表单(C#)中以随机位置添加许多按钮,但是这些按钮之间没有重叠,所以问题是我可以知道该点是否为空或该点已经存在对象吗?

Try something like this out:

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

}

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