示例使用計時器執行簡單倒計時
public partial class Form1 : Form
{
Timer myTimer = new Timer();
int timeLeft = 10;
public Form1()
{
InitializeComponent();
//set properties for the Timer
myTimer.Interval = 1000;
myTimer.Enabled = true;
//Set the event handler for the timer, named "myTimer_Tick"
myTimer.Tick += myTimer_Tick;
//Start the timer as soon as the form is loaded
myTimer.Start();
//Show the time set in the "timeLeft" variable
lblCountDown.Text = timeLeft.ToString();
}
private void myTimer_Tick(object sender, EventArgs e)
{
//perform these actions at the interval set in the properties.
lblCountDown.Text = timeLeft.ToString();
timeLeft -= 1;
if (timeLeft < 0)
{
myTimer.Stop();
}
}
}
結果是…
等等…