C#秒表问题
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;
using System.Diagnostics;
namespace huida
{
public partial class miaobiao : Form
{
public miaobiao()
{
InitializeComponent();
}
Timer time = new Timer();
Stopwatch sw;
TimeSpan ts;
static int count = 1;
private void Form1_Load(object sender, EventArgs e)
{
btnAdd.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
}
private void btnAdd_Click(object sender, EventArgs e) //单击button把时间添加到//dataGridView中
{
string[] arry = { (count++).ToString(), string.Format("{0}:{1}:{2}:{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds)};
dataGridView1.Rows.Add(arry);
}
void time_Tick(object sender, EventArgs e)
{
ts=sw.Elapsed;
label2.Text = string.Format("{0}:{1}:{2}:{3}",ts.Hours,ts.Minutes,ts.Seconds,ts.Milliseconds);
}
private void button1_Click(object sender, EventArgs e) //开始计时
{
sw = new Stopwatch();
time.Tick += new EventHandler(time_Tick);
枝仔 time.Interval =1;
sw.Start();
time.Start();
btnAdd.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
}
private void button2_Click(object sender, EventArgs e) ////复位秒表
{
sw.Stop();
time.Stop();
label2.Text = string.Format("{0}:{1}:{2}:{3}",0,0,0,0);
祥陆 dataGridView1.Rows.Clear();
count = 1;
}
private void button3_Click(object sender, EventArgs e) //暂停或继续秒表
{
if (button3.Text=="暂停")
{
sw.Stop();
time.Stop();
button3.Text = "继续";
谨搭顷 }
else
{
sw.Start();
time.Start();
button3.Text = "暂停";
}
}
}
}
程序界面可以参考下面:
希望对你有帮助。
2023-06-12 广告
button1_click事件中,首先记下当前耐吵时间T0(精确到ms)作为初始时间,同时启动Timer1;
Timer1实现每隔1ms读取当前时间T1(精确到ms),然后T1-T0算出已走时间(ms数),并将其格式化段简为HH:mm:ss fff,显示在label1上;
在button2_click事件中,与上面类似,T1-T0算出一个ms,格式握亩裤化后输出到datagridview中即可。