C#中計時器的使用
1.在Form1的Form1_Load(object sender, EventArgs e)事件中調用方法 InitializeTimer()//調用這個方法將啟用計時器;
2.創建方法
private void InitializeTimer()
{
// 調用本方法開始用計算器
Timer1.Interval = 1000;//設置時鍾周期為1秒(1000毫秒)
Timer1.Tick += new EventHandler(Timer1_Tick);
// Enable timer.
Timer1.Enabled = true;
Button1.Text = "Stop";
Button1.Click += new EventHandler(Button1_Click);
}
3.加入需要定時執行的方法
private void Timer1_Tick(object Sender, EventArgs e)
{
// Set the caption to the current time.
Label1.Text = DateTime.Now.ToString();
}
4.用一個按鈕來控制時鍾的開始與暫停
private void Button1_Click(object sender, EventArgs e)
{
if (Button1.Text == "Stop")
{
Button1.Text = "Start";
Timer1.Enabled = false;
}
else
{
Button1.Text = "Stop";
Timer1.Enabled = true;
}
}
沒技術含量,只是自己學生記錄之用,新手學習難免有錯,如果您發現了錯誤請告知我,非常感謝! 也希望大家能一起學習!!!
