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

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

本文介绍了在C#中的Windows自定义控件窗体鼠标事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有当鼠标进入并回到白离开时改变背景色Panel控件一个的mouseenter和MouseLeave事件。

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.

我有Label控件该面板内部以及但是,当鼠标进入Label控件,为面板火灾MouseLeave事件。

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?

推荐答案

您可以使用GetChildAtPoint()来确定如果鼠标在子控件。

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

如果控制实际上不是一个子控件,你仍然可以使用MousePosition和PointToScreen以确定是否鼠标仍然在控制的范围之内。

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

这篇关于在C#中的Windows自定义控件窗体鼠标事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:05