c#判定鼠标在控件上,在C#中的Windows自定义控件窗体鼠标事件问题

I have a mouseenter and mouseleave event for a Panel control that changes the backcolor when the mouse enters and goes back to white when it leaves.

I have Label control within this panel as well but when the mouse enters the Label control, the mouseleave event for the panel fires.

This makes sense but how do I keep the backcolor of the Panel the same when the mouse is in its area without the other controls inside affecting it?

解决方案

You can use GetChildAtPoint() to determine if the mouse is over a child control.

private void panel1_MouseLeave(object sender, EventArgs e)

{

if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null)

{

panel1.BackColor = Color.Gray;

}

}

If the control isn't actually a child control, you can still use MousePosition and PointToScreen to determine if the mouse is still within the bounds of the control.

private void panel1_MouseLeave(object sender, EventArgs e)

{

Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size);

if (!screenBounds.Contains(MousePosition))

{

panel1.BackColor = Color.Gray;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值