Button Hover Color Change with an animation c#

前端 未结 2 1763
深忆病人
深忆病人 2021-01-29 09:19

i\'v created a windows form and it has 3 buttons. So an one button i figured to change the color with using mouseenter event. that\'s work fine. but i need to change the color w

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 09:49

    Here is some code to get you going: It brings in a new Color by blending the alpha channel.

    public Form1()
    {
        InitializeComponent();
        oldColor = button1.BackColor;
    }
    
    
    Color oldColor;
    Color newColor = Color.FromArgb(0, Color.MediumAquamarine);  // your pick, including Black
    int alpha = 0;
    
    private void button1_MouseEnter(object sender, EventArgs e)
    {
        alpha = 0;
        timer1.Interval = 15;
        timer1.Start();
    }
    
    private void button1_MouseLeave(object sender, EventArgs e)
    {
        timer1.Stop();
        button1.BackColor =  oldColor;
        button1.ForeColor = Color.Black;
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        alpha += 17;  // change this for greater or less speed
        button1.BackColor = Color.FromArgb(alpha, newColor);
        if (alpha >= 255) timer1.Stop();
        if (button1.BackColor.GetBrightness() < 0.3) button1.ForeColor = Color.White;
    }
    

    Edit: If you set the newColor to something too dark the last tick line will set the ForeColor to White now.

    Edit 2: To apply the same animation to several Buttons:

    • Add a class variable Button curButton;
    • Have the MouseEnter and MouseLeave events of all Buttons point to the very same events above
    • Add this line at the top of MouseEnter : Button curButton = (Button) sender;
    • Change each occurence of button1 to curButton.

    To have an individual new Color for each Button

    • Store the newColors it in the Buttons' Tags instead of a class variable:

      • button1.Tag = Color.MediumAquamarine;
      • button2.Tag = Color.MediumSeaGreen; //..etc..
    • Add this to the MouseEnter: newColor = (Color)curButton.Tag; as 2nd line

    I'm beginning to like the whole thing, though not with black ;-)

提交回复
热议问题