2017-06-20 125 views
0

为什么这个无限的彩虹背景循环无法正常工作,我在C#窗体中运行此代码,想法是在单击button1后变换背景颜色。我尝试了不同的无限循环制造商:for(;;)。但这里是代码:C#无限彩虹背景循环

private void button1_Click(object sender, EventArgs e) 
 
     { 
 
    while (true) 
 
    { 
 
     this.BackColor = System.Drawing.Color.Red; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.DarkRed; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.Orange; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.Yellow; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.Green; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.DarkGreen; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.Blue; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.DarkBlue; 
 
     System.Threading.Thread.Sleep(250); 
 
     this.BackColor = System.Drawing.Color.Violet; 
 
    }

谢谢。

+0

运行此代码的应用程序的类型是什么? – ali

+3

这种“不起作用”是如何体现的? –

+0

此代码在哪里运行?在'OnPaint'? –

回答

3

我认为这是Windows窗体,你不能做Thread.Sleep(n)因为睡眠是你的表格,你需要的是一个Timer,一个快速和肮脏的方式来解决你的问题

public List<Color> colors = new List<Color> { 
    Color.Red, 
    Color.DarkRed, 
    Color.Orange 
}; 

private int current; 
private Timer t = new Timer(); 
public Form1() { 
    InitializeComponent(); 
    t.Interval = 250; 
    t.Tick += T_Tick; 

} 

private void T_Tick(object sender, System.EventArgs e) { 
    this.BackColor = colors[current++]; //change to rainbows other colors 
    current %= colors.Count; // rainbow does not have infinite color, we should start again somewhere 
} 

*your_click_method* { 
    t.Start(); 
} 
+0

谢谢,但是在点击button1之后需要启动彩虹,如:private void button1_Click(object sender,EventArgs e) {// here code} –

+0

I编辑答案 – tetralobita

0
从这个意志

除了肯定看起来很可怕, 你的无限循环会阻塞gui线程,所以gui永远不会被更新。 这意味着您的程序没有时间应用更改后的背景颜色。

假设您正在使用Windows窗体,您应该将间隔为250毫秒的计时器拖放到窗体上。 然后存储你的颜色在数组中,无论名单并使其那种形式的成员......

private List<Color> rainbowColors = new List<Color>() 
     { 
      Color.Red, 
      Color.DarkRed, 
      .... 
     }; 

您还需要一个索引知道哪些颜色你正在展示。

private int rainbowIndex; 

在您的计时器事件做这样的事情:因此,对每一个定时器间隔

private void timer_Elapsed(object sender, EventArgs e) 
{ 
    this.BackColor = this.rainbowColors[this.rainbowIndex++]; 
    this.rainbowIndex = this.rainbowIndex % this.rainbowColors.Count; 

    this.Invalidate(); //Really change the formcolor 
} 

你会走得更远一种颜色和复位,如果显示的最后一种颜色。

+1

我想你忘了增加你的索引。 –

+0

这绝对是正确的;)改变它 – feal

+1

更容易:'BackColor = rainbowColors [(rainbowIndex ++)%rainbowColors.Count]' – Rotem