我一直在尝试制作拖放游戏。我有4个面板和4个标签。您必须将标签拖到正确面板的顶部。
问题是检查面板顶部是否有标签。用户可以自由拖动标签。
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;
}
}
这是我用来移动控件的代码。我不得不提到这是一个测试项目,因此我使用了按钮而不是标签,但是想法是相同的。
有什么办法可以检查某个控件是否位于另一个控件之上?
答案 0 :(得分:1)
要检查鼠标是否在控件上,可以检查Cursor.Position
是否在控件的ClientRectangle
中,但首先需要调用控件的PointToClient
方法相对于面板的(0,0)
转换光标位置,例如:
var b = panel1.ClientRectangle.Contains(panel1.PointToClient(Cursor.Position));
可以在用于移动控件的同一事件处理程序中检查标志,例如:
if(b) panel1.BackColor = Color.Red; else panel1.BackColor = Color.Gray;
答案 1 :(得分:1)
每次移动之后,只需从按钮和面板的Bounds属性中获取Rectangle,然后使用Intersect()或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;
}
}
}