Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
how do i change background color of forms every second using threads?
Posted
Comments
Debabrata_Das 6-Jun-14 3:58am    
Hello friend, changing background color of a form is understandable. But I didn't understand the requirement of having Threads. Please add some more details regarding your question. Then we can help you out. :)
- DD

You have to add a Timer control on your form and set the Tick interval as 1 second. Then write background color check logic inside the Timer_Tick() event. This should solve your problem. Let me know if you need more details.
- DD
 
Share this answer
 
You don't: threading is not a good idea here as you can't access Controls (and a Form is a Control) except from the thread they were created on: the UI thread. If you try, you will get a Cross Thread Operation Exception - or you will have to Invoke the UI thread to do it for you, which moves the execution onto the UI thread, making you use of threading superfluous anyway!

Use a Timer instead - the Tick event can change the form background - and forget about threading for the moment.
 
Share this answer
 
Try this code:

C#
int red = 0, green = 0, blue = 0;
private void timer1_Tick(object sender, EventArgs e)
{
    Random rnd = new Random();
    red = rnd.Next(0,256);
    green = rnd.Next(0,256);
    blue = rnd.Next(0,256);
    this.BackColor = Color.FromArgb(red, green, blue);
}
 
Share this answer
 
<text>Try this Code
C#
public Form1()
{
      this.BackColor = Color.Green;
      InitializeComponent();
      var timer = new Timer();
      timer.Interval = 1000;
      timer.Tick += new EventHandler(timer_Tick);
      timer.Start();
   }

  void timer_Tick(object sender, EventArgs e)
  {
      var colors = new[] { Color.Yellow, Color.Green};
      var index = DateTime.Now.Second % colors.Length;
      this.BackColor = colors[index];
  }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900