Search code examples
c#winformslabelmouseenter

c# - WinForms MouseEnter this.label.BackColor


I want to change the BackColor of about 10 or more labels, but I do not want to write a new private void label6_MouseEnter(object sender, EventArgs e) function for each single label.

How do I address in one single function, the current label that the mouse enters uppon? Is this possible?

I thought something the lines of this.label.BackColor = Color.FromArgb(0,0,0); but this does not address the label..


Solution

  • Put few labels on a form and in the code behind write this:

    public partial class Form1 : Form
    {
        public Color OriginalBackground;
    
        public Form1()
        {
            InitializeComponent();
            foreach (var control in Controls.OfType<Label>())
            {
                control.MouseEnter += label_MouseEnter;
                control.MouseLeave += label_MouseLeave;
            }
        }
    
        private void label_MouseEnter(object sender, EventArgs e)
        {
            OriginalBackground = ((Label) sender).BackColor;
            ((Label) sender).BackColor = Color.Red;
        }
    
        private void label_MouseLeave(object sender, EventArgs e)
        {
            ((Label) sender).BackColor = OriginalBackground;
        }
    }