I am creating a game that requires me to change the background color of a panel, wait 1 second, then change it back. The code I tried was:

button1.BackColor = Color.Blue;
System.Threading.Thread.Sleep(1000);
button1.BackColor = Color.DimGray;  //Dim Gray is the original color

When I use this code it never switches to blue, it just stays the Dim Gray.

I also tried overlaying another Panel colored blue over every panel and setting visibility to false. I then used:

button18.Visible = true;
System.Threading.Thread.Sleep(1000);
button18.Visible = false;

Again I got the same result, the panel just stayed Dim Gray. Any help is appreciated.

The reason is you never give the system time to redraw the panel, it immediately goes into sleep mode, then changes the panel back. Insert Application.DoEvents(); after each line where you change the color.

You are also going to find that your GUI 'locks up' during the time where the panel color is changed. You'll have to deal with threading if you don't want that to happen.

Why not use a simple timer?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Timer myTimer = new System.Windows.Forms.Timer();

        public Form1()
        {
            InitializeComponent();
            button1.BackColor = Color.DimGray;
            myTimer.Interval = 1000; // Tick every sec
            myTimer.Enabled = false;
            myTimer.Tick += new EventHandler(TheTimerTicked);
        }

        void TheTimerTicked(object sender, EventArgs e)
        {
            button1.BackColor = Color.DimGray; //reset color
            myTimer.Stop(); //only one tick
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.BackColor = Color.Blue;
            myTimer.Enabled = true; //start the timer
        }
    }
}

You could also try to implement MouseHover and MouseLeave events:

private void button1_MouseHover(object sender, EventArgs e)
        {
            button1.BackColor = Color.Blue;
        }

        private void button1_MouseLeave(object sender, EventArgs e)
        {
            button1.BackColor = Color.DimGray;
        }

Thanks, the

Application.DoEvents();

worked perfectly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.