Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of label when hover and clicked

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.

like image 372
FutureDev Avatar asked Feb 05 '23 03:02

FutureDev


1 Answers

I use this technique, just tested it and I think its what you want.

    Label clickedLabel;
    private void mouseEnter(object sender, EventArgs e)
    {
        Label theLabel = (Label)sender;
        if (theLabel != clickedLabel)
            theLabel.BackColor = Color.Red;
    }

    private void mouseLeave(object sender, EventArgs e)
    {
        Label theLabel = (Label)sender;
        if (theLabel != clickedLabel)
            theLabel.BackColor = Color.Yellow;
    }

    private void labelClick(object sender, EventArgs e)
    {
        setColor();//Calling this here so clickedLabel is still the old value
        Label theLabel = (Label)sender;
        clickedLabel = theLabel;
    }

    public void setColor()
    {
        if(clickedLabel != default(Label))
            clickedLabel.BackColor = Color.Yellow;
        //Resetting clicked label because another (or the same) was just clicked.
    }

Explanation:
These events are only set to labels so we can do (Label)sender which means label that activated the event. I made a Label clickedLabel variable and set it to the clicked label, as soon as the other is clicked the variable will change and the checks will work.

Best thing about this method is it doesn't matter how many Labels you have, you never reference them as name only as sender.

like image 76
EpicKip Avatar answered Feb 07 '23 17:02

EpicKip