Search code examples
c#winformspanel

Check if a control is on top of another


I've been trying to make a drag and drop game. I have 4 panels and 4 labels. You have to drag the labels on top of the correct panel.

The problem is checking if a label is on top of the panel. The user can frely drag the labels.

private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            button1.Left = e.X + button1.Left - MouseDownLocation.X;
            button1.Top = e.Y + button1.Top - MouseDownLocation.Y;
        }
    }

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

Here is the code i used to move the control. I have to mention that this is a test project, so I used a button instead of a label, but the idea is the same.

Is there any way if I can check whether a control is on top of another or not ?


Solution

  • After each move, simply get the Rectangle from the Bounds property of your button and panel, then use either Intersect() or Contains():

        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                button1.Location = new Point(e.X + button1.Left - MouseDownLocation.X, e.Y + button1.Top - MouseDownLocation.Y);
                Rectangle btnRC = button1.Bounds;
                Rectangle pnlRC = panel1.Bounds;
    
                // see if the rectangles INTERSECT
                if (pnlRC.IntersectsWith(btnRC))
                {
                    panel1.BackColor = Color.Green;
                }
                else
                {
                    panel1.BackColor = this.BackColor;
                }
    
                // see if the panel COMPLETELY CONTAINS the button
                if (pnlRC.Contains(btnRC))
                {
                    panel1.BackColor = Color.Green;
                }
                else
                {
                    panel1.BackColor = this.BackColor;
                }
            }
        }