1. 程式人生 > 其它 >c#定時器簡單例子

c#定時器簡單例子

int count; //用於定時器計數
int time; //儲存設定的定時值

private void Form1_Load(object sender, EventArgs e)
{
int i;
for (i = 1; i < 100; i++) //計數範圍 0-99
{
comboBox1.Items.Add(i.ToString() + " 秒"); //初始化下拉框內容
}
//label3.Text = "";
//comboBox1.Text = "1 秒";
}

private void timer1_Tick(object sender, EventArgs e) //定時器事件
{
//記錄當前秒
count++;
label3.Text = (time - count).ToString() + "秒";//顯示剩餘時間
progressBar1.Value = count; //設定進度條進度
if(count == time)
{
timer1.Stop(); //時間到,停止計時
System.Media.SystemSounds.Asterisk.Play(); //提示音
MessageBox.Show("時間到了!","提示"); //彈出提示框
}
}

private void button1_Click(object sender, EventArgs e)//開始計時按鈕事件
{
string str = comboBox1.Text; //將下拉框內容新增到一個變數中
string data = str.Substring(0, 2);    //從0開始擷取兩位
time = Convert.ToInt32(data); //得到設定定時值(整型)
progressBar1.Maximum = time; //進度條最大數值
timer1.Start(); //開始計時
}
}

菜鳥小白,當筆記記錄,如有問題,歡迎留言。