Change color of label when hover and clicked

FutureDev picture FutureDev · Feb 6, 2017 · Viewed 7.5k times · Source

I have a problem regarding changing appearance of a label. Here is the screenshot:

enter image description here

That is the color when you hover the mouse and I want it like that. What I want is for it to stay that color when I clicked it. But because of my mouseleave control it would not work like I want it.

Here is the code:

   private void btnArchives_MouseEnter(object sender, EventArgs e)
    {
        lblArchives.BackColor = Color.FromArgb(9, 18, 28); //darkercolor
    }

   private void btnArchives_MouseLeave(object sender, EventArgs e)
   {
       lblArchives.BackColor = Color.FromArgb(15, 34, 53); //lightercolor
   }

I tried mouse hover too. It looked the same as mouse enter though. Bottom line is I want the color to change to the darker color when hovered over them and change back to the lighter color when hovered out of them. But I also what it to stay dark color when I clicked it. And then turn back to lighter color then I click another button and that other button will now turn to darker color. Thank you!

EDIT: i used label instead of buttons. Im currently trying some of the comments below thank you very much.

Answer

KernelMode picture KernelMode · Feb 6, 2017

You can remove the event handlers btnArchives_MouseLeave and button1_MouseEnter when button clicked to prevent it. But you need to add it back when the button is clicked again:

private void btnArchives_Click(object sender, EventArgs e)
{
            if (!clicked)
            {
                btnArchives.MouseEnter-= new EventHandler(btnArchives_MouseEnter);
                btnArchives.MouseLeave-= new EventHandler(btnArchives_MouseLeave);
                clicked = true;
                return;
            }

            btnArchives.MouseEnter += new EventHandler(btnArchives_MouseEnter);
            btnArchives.MouseLeave += new EventHandler(btnArchives_MouseLeave);
            clicked = false;
  }

  void btnArchives_MouseLeave(object sender, EventArgs e)
  {
              this.btnArchives.BackColor = Color.FromArgb(15, 34, 53);
  }

  void btnArchives_MouseEnter(object sender, EventArgs e)
  {
              this.btnArchives.BackColor = Color.FromArgb(9, 18, 28);
  }