Search code examples
c#multithreadingwinformstimer

I want to change backcolor every 1 second in winform using timer


I want to change backgroundcolor every 1 second using timer in winform. For example Red -> SystemColors.Control -> red -> SystemColors.Control ->..

I have menuitem in mainUI. So when I click this control, I want to see automatically changing of mainUI's background color.

Here is code what I wrote. what should I change in this code?

private void RadMenuItem9_Click(object sender, EventArgs e)
{
    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    timer.Enabled = true;
    timer.Interval = 2000;
    timer.Tick += new EventHandler(Timer1_Tick);
    timer.Start();
}

private void Timer1_Tick(object sender, EventArgs e)
{
    BackColor = Color.Red;
    Thread.Sleep(1000);
    BackColor = SystemColors.Control;
}

Solution

  • You need to make logic for switching colors. Here since you want to change between two colors you can check the current color and switch to the other. You can’t use Sleep since that will block the UI thread and no changes will be shown on screen while the thread is blocked.