Search code examples
c#windowswinformsbackground-coloronmouseover

Changing button background color on mouse-over event


I am developing a project in C# Windows applications (WinForms) in that I need to create a function to change the background color for all the buttons that are in the single form using button mouse-over event. How do I do that?


Solution

  • Changing all controls of type Button:

    for (int i = 0; i < Controls.Count; i++)
                if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
    

    Example of hooks:

    MouseEnter += new EventHandler(delegate(object sender, EventArgs e)
        {
            SetButtonColour(Color.Blue);
        });
    
    MouseLeave += new EventHandler(delegate(object sender, EventArgs e)
        {
            SetButtonColour(Color.Red);
        });
    
    public void SetButtonColour(Color colour)
        {
            for (int i = 0; i < Controls.Count; i++)
                if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
        }