2017-07-14 57 views
0

我有一個標籤彈出讓用戶點擊複製按鈕,它已被複制使用應用程序右下角的標籤。但我希望文字在2秒左右後消失。然後回來,如果他們再次點擊複製,這是我的副本按鈕代碼:C#如何使用標籤上的用戶計時器?

 private void copyBtn_Click(object sender, EventArgs e) 
    { 
     labelCopied.Text = "Copied to Clipboard!"; 
     Clipboard.SetText(btcTxtBox.Text); 
     SystemSounds.Hand.Play(); 

    } 

我知道labelCopied.Text.Remove(0);將清除的標籤,但我無法弄清楚如何使用定時器

回答

2

使用Timer此實現它:

private void copyBtn_Click(object sender, EventArgs e) 
{ 
    labelCopied.Text = "Copied to Clipboard!"; 
    Clipboard.SetText(btcTxtBox.Text); 
    SystemSounds.Hand.Play(); 

    Timer t = new Timer(); 
    t.Interval = 2000; //2000 milliseconds = 2 seconds 
    t.Tick += (a,b) => 
    { 
     labelCopied.Text = string.Empty; 
     t.Stop(); 
    }; 

    t.Start(); 
} 

編輯

Task.Delay內部使用一個Timer。所以如果你不介意最小的性能開銷,Task.Delay是很好的去。此外Task.Delay更便攜,因爲TimerWinForms特定的(在WPF你會使用DispatcherTimer

private async void copyBtn_Click(object sender, EventArgs e) 
{ 
    labelCopied.Text = "Copied to Clipboard!"; 
    Clipboard.SetText(btcTxtBox.Text); 
    SystemSounds.Hand.Play(); 
    await Task.Delay(2000); 
    labelCopied.Text = ""; 
} 
+0

謝謝,這將你推薦它是WinForms自然。計時器或Task.Delay? –

+0

'Task.Delay'在內部使用'Timer'。所以如果你不介意最小的性能開銷,那麼'Task.Delay'是很好的選擇。另外'Task.Delay'更具可移植性,因爲'Timer'是'WinForms'特定的(在'WPF'中你可以使用'DispatcherTimer') –

+0

謝謝,比線程休眠好得多,因爲它暫停了應用程序。 –

1

假設的WinForms,用async/awaitTask.Delay(),像這樣:

private async void copyBtn_Click(object sender, EventArgs e) 
{ 
    labelCopied.Text = "Copied to Clipboard!"; 
    Clipboard.SetText(btcTxtBox.Text); 
    SystemSounds.Hand.Play(); 
    await Task.Delay(2000); 
    labelCopied.Text = ""; 
}