2016-03-06 58 views
3

我想在c#中的遊戲應用程序中插入更改按鈕顏色2000毫秒的延遲...我應該使用什麼命令? (我想更改按鈕的顏色,持續2秒,然後回到正常狀態)謝謝如何在c#中爲命令創建延遲?

 switch (colorNum) 
     { 
      case 1: 
       btnRed.BackColor = Color.Red 

       btnRed.BackColor = Color.LightCoral; 
       firedColors[count] = "Red"; 
       count++; 
       break; 
      case 2: 
       btnBlue.BackColor = Color.Blue; 

       btnRed.BackColor = Color.LightBlue; 
       firedColors[count] = "Blue"; 
       count++; 
       break; 
      case 3: 
       btnYellow.BackColor = Color.Gold; 

       btnYellow.BackColor = Color.LightYellow; 
       firedColors[count] = "Yellow"; 
       count++; 
       break; 
     } 
+0

你可以使用'Thread.Sleep',例如'Thread.Sleep(1000)'增加1秒的延遲。 –

+0

它掛出程序...我不知道爲什麼?? !!! –

+0

這是正確的,它暫停UI線程。我昨天回答了類似的問題[這裏](http://stackoverflow.com/a/35814366/4422347)遵循這個建議。 –

回答

2

這裏有一種方法,你可以用async - await做到這一點:

using System.Threading.Tasks; 

async void YourFunction() // <--- Use "async" keyword 
{ 
    switch (colorNum) 
    { 
     case 1: 
      btnRed.BackColor = Color.Red; 
      await Task.Delay(2000); 
      btnRed.BackColor = Color.LightCoral; 
      firedColors[count] = "Red"; 
      count++; 
      break; 
     case 2: 
      btnBlue.BackColor = Color.Blue; 
      await Task.Delay(2000); 
      btnRed.BackColor = Color.LightBlue; 
      firedColors[count] = "Blue"; 
      count++; 
      break; 
     case 3: 
      btnYellow.BackColor = Color.Gold; 
      await Task.Delay(2000); 
      btnYellow.BackColor = Color.LightYellow; 
      firedColors[count] = "Yellow"; 
      count++; 
      break; 
    } 
} 

注:此代碼使用.Net版本4.5及以上。

+0

非常感謝:) –

0

使用Timer來管理顏色更改過程,並在每次更改後進行處理,如果不打算頻繁更改。既然你沒有提到你要改變顏色,我把代碼放在Button

private Color _originalColor = Color.LightGray; 
private Color _newColor = Color.LightSkyBlue; 
private bool _isOrigColor = true; 
Timer _tmrChangeColor; 

private void btnTest_Click(object sender, EventArgs e) 
{ 
    if (_tmrChangeColor != null) return; 
    _tmrChangeColor = new Timer {Interval = 2000, Enabled = true}; 
    _tmrChangeColor.Tick += _tmrChangeColor_Tick; 
} 

void _tmrChangeColor_Tick(object sender, EventArgs e) 
{ 
    btnTest.BackColor = _isOrigColor ? _newColor : _originalColor; 
    _isOrigColor = !_isOrigColor; 
    _tmrChangeColor.Dispose(); 
    _tmrChangeColor = null; 
}