核心代码:
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
using System.Diagnostics;
using Timer = System.Windows.Forms.Timer;
namespace StopWatch
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
sw = new Stopwatch();
time.Tick += new EventHandler(time_Tick);
time.Interval = 1;
}
Timer time = new Timer();
Stopwatch sw; //秒表
TimeSpan ts;//计时
private void Start_Click(object sender, EventArgs e)
{
if (Start.Text=="Start")
{
sw.Reset();
time.Stop();
sw.Start();
time.Start();
}
else if (Start.Text=="Continue")
{
sw.Start();
time.Start();
}
}
void time_Tick(object? sender, EventArgs e)
{
ts = sw.Elapsed;
timeLabel.Text = string.Format("{0}:{1}:{2}:{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
}
private void Suspend_Click(object sender, EventArgs e)
{
Start.Text = "Continue";
sw.Stop();
time.Stop();
}
private void End_Click(object sender, EventArgs e)
{
Start.Text = "Start";
sw.Stop();
time.Stop();
timeLabel.Text = string.Format("{0}:{1}:{2}:{3}", 0, 0, 0, 0);
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
sw.Stop();
time.Stop();
}
}
}