Search code examples
c#buttonbackcolor

Change button color for a short time


I would like to change the backgroundcolor of a button for a couple of seconds to lime and then change it back to normal. For some reason it simply doesnt work, I have to wait for those seconds and some things I tested also work but the backgroundcolor isn't changed. This is what I've tried so far:

private void button1_Click(object sender, EventArgs e)
{
    button1.BackColor = Color.Lime;
    Thread.Sleep(2000);
    button1.BackColor = SystemColors.Control;
}

Hopefully someone can help me out with this!


Solution

  • You need a timer. Add a timer control from the toolbox to your form. Double-click on it to add a timer tick event handler

        private void button1_Click(object sender, EventArgs e)
        {
            button1.BackColor = Color.Lime;
            //Set time between ticks in miliseconds.
            timer1.Tick=2000;
            //Start timer, your program continues execution normaly
            timer1.Start;
            //If you use sleep(2000) your program stop working for two seconds.
    
        }
            //this event will rise every time set in Tick (from start to stop)
            private void timer1_Tick(object sender, EventArgs e)
            {
              //When execution reach here, it means 2 seconds have passed. Stop timer and change color
              timer1.Stop;
              button1.BackColor = SystemColors.Control;
            }