计时器

来源:互联网 发布:html5 输入框遮挡js 编辑:程序博客网 时间:2024/04/30 14:39

先在窗口中加入一个计时器控件:(timer1)用于触发计时;一个Label控件:(bable1)用于显示时间;两个按钮:(btnStar)用于开始/停止计时,(btnClear)用于计时器清零。

        声明一个整型变量:t,用于获取毫秒,然后在窗口代码中加入以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 计时器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private int t = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            this.timer1.Enabled = false;
            this.timer1.Interval = 1;
        }
        //计时函数
        public string GetAllTime(int time)
        {
           string senconds,minutes,hours;
           int s= time /100;
           int m = s / 60;
           int h = m / 60;
           s = s % 60;
           if (s < 10)//秒格式00
               senconds ="0"+ s.ToString();
           else
               senconds = s.ToString();
           if (m < 10)//分格式00
               minutes = "0" + m.ToString();
           else
               minutes = m.ToString();
           if (h < 10) //时格式00
               hours = "0" + h.ToString();
           else
               hours = h.ToString();
            return hours+":"+minutes+":"+senconds;
        }
      
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled == false)
            {
                this.btnStart.Text = "停止计时";
                this.timer1.Enabled = true;
            }
            else
            {
                this.btnStart.Text = "开始计时";
                this.timer1.Enabled = false;
            }   
           
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            t = t + 1;
            this.babel1.Text=GetAllTime(t);  
   
        }

        private void button2_Click(object sender, EventArgs e)
        {
            t = 0;
            if (this.timer1.Enabled == true)
            {
                this.btnStart_Click(sender, e);
                babel1.Text = GetAllTime(t);
            }
            else babel1.Text = GetAllTime(t);
        }

    }
}

 

原创粉丝点击