Home > database >  Change background color of control regardless if mouse is over a child control
Change background color of control regardless if mouse is over a child control

Time:11-21

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

CodePudding user response:

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.

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.

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:

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

This is the demo of Test form (with and without foreach...): enter image description here

  • Related