TimeSpan(一个简单的计时器)
1.如下图所示:
总时长=运行时长加上暂停时长;
暂停时长在每次点击暂停的时候叠加;
2.代码如下:
TimeSpan TimeStart;TimeSpan TimeStop;//暂停时间点TimeSpan TimeStops;//暂停总时长TimeSpan TimeOver;//总时间TimeSpan TimeOvers;//总时间减去暂停时间DateTime timeStop;//暂停计时bool isStop = false;/// <summary>/// 开始/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){timer1.Enabled = true;DateTime time = DateTime.Now;TimeStart = new TimeSpan(time.Ticks);}/// <summary>/// 暂停/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){isStop = true;TimeStop = new TimeSpan(DateTime.Now.Ticks).Add(-TimeStops);}/// <summary>/// 继续/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){isStop = false;TimeStops = new TimeSpan(DateTime.Now.Ticks).Subtract(TimeStop);}/// <summary>/// 结束/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button4_Click(object sender, EventArgs e){//TimeOver = new TimeSpan(DateTime.Now.Ticks).Subtract(TimeStops);}private void timer1_Tick(object sender, EventArgs e){if (isStop){TimeStops = new TimeSpan(DateTime.Now.Ticks).Subtract(TimeStop).Duration() ;int v= (int)TimeStops.TotalHours;textBox_StopNum.Text = $"{v:F0}:{TimeStops.Minutes}:{TimeStops.Seconds}";}else{TimeOver = new TimeSpan(DateTime.Now.Ticks).Subtract(TimeStart).Duration();TimeOvers = TimeOver.Subtract(TimeStops);int hour = (int)TimeOver.TotalHours;textBox_TimeNum.Text = $"{hour:F0}:{TimeOver.Minutes}:{TimeOver.Seconds}";textBox_Run.Text = $"{TimeOvers.TotalHours:F0}:{TimeOvers.Minutes}:{TimeOvers.Seconds}";}}