简体   繁体   English

无论鼠标是否在子控件上,都更改控件的背景颜色

[英]Change background color of control regardless if mouse is over a child control

I am making a custom control, the idea is that when mouse is over the control, the background color is different and when mouse is not longer over the control then return to the original color.我正在制作一个自定义控件,其想法是当鼠标悬停在控件上时,背景颜色不同,当鼠标不再悬停在控件上时,则返回原始颜色。

One problem is when mouse is over a child control nothing happens一个问题是当鼠标悬停在子控件上时,什么也没有发生

I've tried assigning a common mouseover event handler for all children controls, but anyways when the mouse moves fast nothing happens.我尝试为所有子控件分配一个通用的鼠标悬停事件处理程序,但无论如何,当鼠标快速移动时,什么也没有发生。

I want a behavior similar to button control that no matter how fast the mouse is moving, the background color seems to change with no problem我想要一个类似于按钮控制的行为,无论鼠标移动多快,背景颜色似乎都会毫无问题地改变

All childs must share the same method which MouseEnter event from parent will access, because if not, when your mouse is over childs it will raise MouseLeave event of parent.所有子项必须共享父项的MouseEnter事件将访问的相同方法,因为如果没有,当您的鼠标悬停在子项上时,它将引发父项的MouseLeave事件。

This is an example:这是一个例子:

public partial class Test : Form
{
    public Test()
    {
        InitializeComponent();
        myPictureBox1.MouseEnter += (sender, e) => { AllControls_MouseEnter(); };
        myLabel1.MouseEnter += (sender, e) => { AllControls_MouseEnter(); };
        myLabel2.MouseEnter += (sender, e) => { AllControls_MouseEnter(); };
    }

    private void Panel_MouseEnter(object sender, EventArgs e)
    {
        AllControls_MouseEnter();
    }

    private void Panel_MouseLeave(object sender, EventArgs e)
    {
        AllControls_MouseLeave();
    }

    private void AllControls_MouseEnter()
    {
        Panel.BackColor = Color.Firebrick;
    }

    private void AllControls_MouseLeave()
    {
        Panel.BackColor = Color.White;
    }
}

Of course, myPictureBox1 , myLabel1 and myLabel2 are childs of Panel , as you could figure it out.当然, myPictureBox1myLabel1myLabel2Panel的孩子,你可以理解。

Or if you have a lot of controls, you can iterate thru all Controls collection of parent (it is the method I would choose, instead of assigning to all controls), like this:或者,如果您有很多控件,则可以遍历父级的所有Controls集合(这是我会选择的方法,而不是分配给所有控件),如下所示:

foreach (var c in Panel.Controls)
{
    ((Control)c).MouseEnter += (sender, e) => { AllControls_MouseEnter(); };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM