由于目前用到了C#的有关知识,但之前没有C#的基础,所以趁着机会正好学习学习。
本篇博文,记录下利用C#实现一个简单的秒表计时器,基本界面如下图。
功能说明:点击“开始”开始计时,点击“暂停”暂停计时,点击“”停止“”停止计时,再点击“开始”,重新开始计时。
首先,我们在窗体设计窗口画出该界面,由1个Label,3个button构成。双击按钮添加事件。
核心部分是用秒表对象Stopwatch和时钟Timer实现的。
程序源代码如下:
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 Ch04Ex04
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Timer time = new Timer();
Stopwatch sw; //秒表对象
TimeSpan ts;
static int count = 1;
private void button1_Click(object sender, EventArgs e)
{
//开始按钮
button2.Enabled = true;
button3.Enabled = true;
if(button2.Text == "继续") //开始后将继续按钮重置为暂停
button2.Text = "暂停";
sw = new Stopwatch();
time.Tick += new EventHandler(time_Tick); //时钟触发