Fast and continuous change of the background color of a Panel

Asked

Viewed 438 times

1

I’m trying to get a panel to constantly change color with the following code

while (true)
{
   panelColor.BackColor = Color.Blue;
   Thread.Sleep(500);
   panelColor.BackColor = Color.Red;
   Thread.Sleep(500);
}

The problem is that the application hangs every time it comes to this part, someone can tell me why?

  • This is an infinite loop, the execution will never leave it.

  • theoretically should not keep changing colors with the 500 milliseconds interval in this loop?

  • thanks for the help, that’s right, forgot the refresh

1 answer

2


The application hangs because it is running a loop infinite.

You also don’t see the background changing color for the same reason, as Uithread is blocked from running this code, the windows framework doesn’t have the opportunity to redesign the controls.

Change the code as follows:

while (true)
{
   panelColor.BackColor = Color.Blue;
   panelColor.Refresh();
   Thread.Sleep(500);

   panelColor.BackColor = Color.Red;
   panelColor.Refresh();
   Thread.Sleep(500);
}

The method refresh() makes the control auto redesign itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.