参考:http://zhidao.baidu.com/link?url=j-jxQJenrO54BSKJ_IkXWbhdDqbVLUyyenjjSGs8G0xdisgBZ0EMhzyWgARSFct6rTP5BaabDacbTOvoxhijg_
代码:
一、新建一个WindowsFormsApplication工程
在Design设计区中,从ToolBox拖了四个控件:两个Buttion、一个Label、一个Timer,下面是Form1.cs中自动生成的对应的初始化代码
partial class Form1 { ... ... private System.Windows.Forms.Button button1; private System.Windows.Forms.Label timerShow; private System.Windows.Forms.Button button2; private System.Windows.Forms.Timer timer2; }
二、设计区上双击控件进入对应的方法,所有控件对应的方法代码如下:
public partial class Form1 : Form { System.Diagnostics.Stopwatch sw; TimeSpan ts; public Form1() { InitializeComponent(); timer2.Interval = 1; sw = new System.Diagnostics.Stopwatch(); ts = sw.Elapsed; } private void Form1_Load(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { sw.Start(); timer2.Start(); ts = sw.Elapsed; timerShow.Text = String.Format("{0:00}天{1:00}小时{2}分{3}秒{4}毫秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); } private void button2_Click(object sender, EventArgs e) { sw.Stop(); ts = sw.Elapsed; timerShow.Text = String.Format("{0:00}天{1:00}小时{2:00}分{3}秒{4}毫秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); } private void timer2_Tick(object sender, EventArgs e) { ts = sw.Elapsed; timerShow.Text = String.Format("{0:00}天{1:00}小时{2:00}分{3:00}秒{4}毫秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); timerShow.Refresh(); } }
效果: