0
我的程序有一個參數,用於啓動winform並等待x運行函數之前的秒數。目前,我正在使用線程睡眠功能x秒,然後運行該功能。如何在條狀態標籤中添加一個定時器?帶狀態標籤c中的倒數計時器#
所以,它說:x Seconds Remaining...
我的程序有一個參數,用於啓動winform並等待x運行函數之前的秒數。目前,我正在使用線程睡眠功能x秒,然後運行該功能。如何在條狀態標籤中添加一個定時器?帶狀態標籤c中的倒數計時器#
所以,它說:x Seconds Remaining...
而是阻塞線程執行的,簡單的調用方法時,需要超時通過。將新的Timer
添加到您的表單中,並將它的間隔設置爲1000
。然後訂閱計時器的Tick
事件和事件處理程序計算經過時間:
private int secondsToWait = 42;
private DateTime startTime;
private void button_Click(object sender, EventArgs e)
{
timer.Start(); // start timer (you can do it on form load, if you need)
startTime = DateTime.Now; // and remember start time
}
private void timer_Tick(object sender, EventArgs e)
{
int elapsedSeconds = (int)(DateTime.Now - startTime).TotalSeconds;
int remainingSeconds = secondsToWait - elapsedSeconds;
if (remainingSeconds <= 0)
{
// run your function
timer.Stop();
}
toolStripStatusLabel.Text =
String.Format("{0} seconds remaining...", remainingSeconds);
}
你可以使用一個Timer
:
public class Form1 : Form {
public Form1(){
InitializeComponent();
t = new Timer {Interval = 1000};
t.Tick += Tick;
//try counting down the time
CountDown(100);
}
DateTime start;
Timer t;
long s;
public void CountDown(long seconds){
start = DateTime.Now;
s = seconds;
t.Start();
}
private void Tick(object sender, EventArgs e){
long remainingSeconds = s - (DateTime.Now - start).TotalSeconds;
if(remainingSeconds <= 0) {
t.Stop();
toolStripStatusLabel1.Text = "Done!";
return;
}
toolStripStatusLabel1.Text = string.Format("{0} seconds remaining...", remainingSeconds);
}
}