2016-09-26 271 views
-1

當按鈕被點擊時,我想讓按鈕的顏色在5秒後變成黑色,但我無法讓它工作。我已經將該計時器的時間間隔設置爲5000,並在該屬性中將啓用設置爲true。Visual studio c#timer不起作用

using System; 
using System.Drawing; 
using System.Windows.Forms; 

namespace WindowsFormsApplication4 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 


     private void button1_Click(object sender, EventArgs e) 
     { 
      timer1.Enabled = true; 
      timer1.Start(); 

      button1.BackColor = Color.Black; 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 

     } 
    } 
} 
+0

您正在使用什麼定時器裏面?你應該使用windows.Forms.Timer。看起來您已經在設計時添加了它,請確保您想延遲的操作在Tick Event中。 –

回答

2

最佳soultion會,

private void button1_Click(object sender, EventArgs e) 
     {    
      Timer MyTimer = new Timer(); 
      MyTimer.Interval = 4000; 
      MyTimer.Tick += new EventHandler(MyTimer_Tick); 
      MyTimer.Start(); 

     } 

     private void MyTimer_Tick(object sender, EventArgs e) 
     { 
      button1.BackColor = Color.Black; 

     } 
+0

謝謝!您的解決方案正在工作 – bubibu

+0

@bubibu你可以標記爲答案 – Sajeetharan

2

如果你想要的顏色更改爲黑色,並保持這種方式,5 seconds後,您需要將在timer1_Tick事件處理程序的button1.BackColor分配。另外,不要忘記停止計時器滴答。

private void timer1_Tick(object sender, EventArgs e) 
{ 
     button1.BackColor = Color.Black; 
     timer1.stop(); 
} 
1

試試這個:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 

     button1.BackColor = Color.Black; 
     timer1.Stop(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     timer1.Enabled = true; 
     timer1.Interval = 5000; 
     timer1.Start(); 


    } 
} 

你必須把按鈕的背景色黑色的觸發計時器的Tick事件。

+0

我想'timer1.Stop();'放入Tick事件將會很棒 – Eric

+0

在winforms定時器中,啓用它和啓動兩者都會做同樣的事情。 –

+0

我同意。這是爲了確保計時器只勾選一次:)將更新我的答案。 – Jayson

0

寫的顏色變化碼timer_tick事件

private void timer1_Tick(object sender, EventArgs e) 
    { 
     button1.BackColor = Color.Black; 
     timer1.Enabled = false; 
    }