单击按钮后秒表并重置时间

时间:2012-10-24 14:43:48

标签: c# winforms

我目前正在学习如何使用C#中的秒表属性。我有button1启动秒表。我想将时间重置为0并在第二次点击后重新开始,依此类推。每次连续点击按钮后,我怎样才能重置秒表计时器?

代码

namespace stopwatch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();    
        }

        Stopwatch sw = new Stopwatch();

        private void button1_Click(object sender, EventArgs e)
        { 
            sw.Start();   
            TimeSpan x = sw.Elapsed;
            textBox1.Text = x.ToString();                   
        }                
    }
}

3 个答案:

答案 0 :(得分:1)

使用Stopwatch.StartNew()

请尝试使用这段代码片段:

private void button1_Click(object sender, EventArgs e)
{
    sw = Stopwatch.StartNew();

    // ... do something ...

    sw.Stop();

    textBox1.Text = sw.Elapsed.ToString();
}

答案 1 :(得分:0)

Stopwatch sw = new Stopwatch();
private void button1_Click(object sender, EventArgs e)
{
    sw.Stop();
    TimeSpan x = sw.Elapsed;
    textBox1.Text = x.ToString();

    // >= .NET 4
    sw.Restart();    

    // >=.NET 2.0
    sw.Reset();
    sw.Start();                   
}

答案 2 :(得分:0)

    private void button1_Click(object sender, EventArgs e)
    {
            sw.Stop();

            TimeSpan x = sw.Elapsed;

            textBox1.Text = x.ToString();

            sw.Restart();
     }