2012-08-10 103 views
0

是否有任何方法來改變窗口Form1中背景每1秒後,像這樣:C#如何每1秒後更改Form1背景?

Second 1: Yellow 
Second 2: Green 
Second 3: Yellow 
Second 4: Green 
... 
+0

後臺線程。 – 2012-08-10 02:48:28

+0

對不起,你能用代碼解釋嗎? – Sakura 2012-08-10 02:53:10

+0

綠色和金色! – 2012-08-10 02:56:31

回答

4

嘗試這種情況:

 var timer = new Timer() { Interval = 1000, Enabled = true, }; 
     timer.Tick += (s, e) => 
      this.BackColor = 
        this.BackColor == Color.Green ? Color.Yellow : Color.Green; 
+1

非常簡潔。爲我工作。 – GrayFox374 2012-08-10 03:27:49

3

拖放一個定時器控制到Form1中

設置定時器間隔爲1000毫秒(1秒) 。

private int caseSwitch = 0; 
private void timer1_Tick(object sender, EventArgs e) 
{ 
    caseSwitch++; 
    switch (caseSwitch) 
    { 
     case 1: 
      this.BackColor = Color.Yellow; 
      break; 
     case 2: 
      this.BackColor = Color.Green; 
      break; 
    } 

    if (caseSwitch == 2) caseSwitch = 0; 
} 
1
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]; 
    } 
+0

他使用WinForms,他可以像Jeremy那樣使用拖放。 – 2012-08-10 03:16:09

+0

我個人喜歡當人們給代碼做表單設計 – 2012-08-10 03:16:31

1

正如傑里米所述

拖放一個定時器控制到Form1中和定時器間隔設定爲1000毫秒>(即1秒)。

在計時器滴答的事件處理程序,邏輯可以是這樣的,

private void timer1_Tick(object sender, EventArgs e) 
{ 
    if(this.BackColor == Color.Green) 
      this.BackColor = Color.Yellow; 
    else 
      this.BackColor = Color.Green; 
} 
1
private void button1_Click(object sender, EventArgs e) 
     { 
      timer1.Interval = 1000; 
      timer1.Enabled = true; 
      timer1.Tick += new EventHandler(timer1_Tick); 
      timer2.Interval = 1000; 
      timer2.Tick += new EventHandler(timer2_Tick); 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
       txt_trp.BackColor = Color.Red; 
       txt_trm.BackColor = Color.Yellow; 
       timer2.Enabled = true; 
       timer1.Enabled = false; 
     } 
     private void timer2_Tick(object sender, EventArgs e) 
     { 
       txt_trp.BackColor = Color.Yellow; 
       txt_trm.BackColor = Color.Red; 
       timer1.Enabled = true; 
       timer2.Enabled = false; 
     } 
+0

private void timer1_Tick(object sender,EventArgs e) txt_trp.BackColor = Color.Red; txt_trm.BackColor = Color.Yellow; timer2.Enabled = true; timer1.Enabled = false; } private void timer2_Tick(object sender,EventArgs e) txt_trp.BackColor = Color.Yellow; txt_trm.BackColor = Color.Red; timer1.Enabled = true; timer2.Enabled = false; } – 2015-03-06 17:59:54

+0

這是一個非常複雜的方法來完成這個。只要使用一個計時器,並嚴格地將當前位置存儲在列表中。 – BradleyDotNET 2015-03-06 18:22:31