1. 程式人生 > 實用技巧 >用Windows窗體程式設計簡單的計時器

用Windows窗體程式設計簡單的計時器

實現時間的開始,停止,清零功能

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();//初始化
        }
        public int t = 0;//定義時間初始值
        private void button1_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled)//一開始將timer的Enable屬性設為false
            {
                timer1.Stop();
                button1.Text 
= "開始計時"; button2.Enabled = true; } else {
//一開始滑鼠點選一次timer1開始計時,按鈕文字值變化,清零按鈕失效 timer1.Start(); button1.Text
= "停止計時"; button2.Enabled = false; } }
private void timer1_Tick(object sender, EventArgs e) { t++; label1.Text = GetTimeFormat(t); } public string GetTimeFormat(int t) { string hh, mm, ss, mms; int temp = t/100;//獲取多少秒 int ms = t % 100;//獲取多少毫秒
int h = temp / 3600;//獲取多少小時 int m = temp / 60 % 60;//獲取多少分鐘
int s = temp % 60; if (ms < 10) mms = "0" + ms.ToString(); else mms = ms.ToString(); if (h < 10) hh = "0" + h.ToString(); else hh = h.ToString(); if (m < 10) mm = "0" + m.ToString(); else mm = m.ToString(); if (s < 10) ss = "0" + s.ToString(); else ss = s.ToString(); return hh+":"+mm+":"+ss+"."+mms; } //清零按鈕 private void button2_Click(object sender, EventArgs e) { label1.Text = "00:00:00.00"; t = 0; } }