如何使用线程每秒更改窗体的背景颜色? [英] How Do I Change Background Color Of Forms Every Second Using Threads?
本文介绍了如何使用线程每秒更改窗体的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用线程每秒更改表单的背景颜色?
how do i change background color of forms every second using threads?
推荐答案
您必须添加计时器
控制表单并将Tick间隔设置为1秒。然后在Timer_Tick()事件中写入背景颜色检查逻辑。这应该可以解决您的问题。如果您需要更多详细信息,请告诉我。
- DD
You have to add aTimer
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
您没有:因为您无法访问控件,因此线程不是一个好主意(并且Form是一个Control),除了它们创建的线程:UI线程。如果你尝试,你将得到一个跨线程操作异常 - 或者你将不得不调用UI线程为你做这个,这将执行移动到UI线程,无论如何使你使用线程多余!
使用Timer代替 - Tick事件可以改变表格背景 - 暂时忘记线程。
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.
试试这段代码:
Try this code:
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);
}
这篇关于如何使用线程每秒更改窗体的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文