在C#中设置秒表程序的开始时间 [英] Set start time for Stopwatch program in C#

查看:117
本文介绍了在C#中设置秒表程序的开始时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个简单的秒表程序,我可以使它与以下代码一起使用

I want to write a simple stopwatch program, I can make it work with the following code

    public Form1()
    {
        InitializeComponent();
    }
    System.Diagnostics.Stopwatch ss = new System.Diagnostics.Stopwatch { };
    private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Text == "Start")
        {
            button1.Text = "Stop";

            ss.Start();
            timer1.Enabled = true;

        }
        else
        {
            button1.Text = "Start";

            ss.Stop();
            timer1.Enabled = false;

        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {


            int hrs = ss.Elapsed.Hours, mins = ss.Elapsed.Minutes, secs = ss.Elapsed.Seconds;
            label1.Text = hrs + ":";
            if (mins < 10)
                label1.Text += "0" + mins + ":";
            else
                label1.Text += mins + ":";
            if (secs < 10)
                label1.Text += "0" + secs;
            else
                label1.Text += secs;


    }

    private void button2_Click(object sender, EventArgs e)
    {
        ss.Reset();
       button1.Text= "Start";
       timer1.Enabled = true;

    }

现在,我想为此秒表设置自定义开始时间,例如,我希望它不从0:00:00开始计时,而是从0:45:00开始计时我该怎么办,谢谢.

Now I want to set a custom start time for this stopwatch, for example I want it not to begin count up from 0:00:00 but to start with 0:45:00 How can I do it, thank you.

推荐答案

创建 System.TimeSpan 的初始值为45分钟.比在其中添加秒表的值 TimeSpan.Add方法.方便地, Stopwatch.Elapsed 的类型为System.TimeSpan已经.

Create a new instance of System.TimeSpan with the initial value of 45 minutes as per you example. Than add the value of the stopwatch to it TimeSpan.Add Method. Conveniently the Stopwatch.Elapsed is of type System.TimeSpan already.

比使用字符串格式化程序将格式化的时间打印到标签中.我认为其他答案之一已经显示了如何执行此操作.否则,这里有一些有关如何格式化TimeSpan实例的很好的参考TimeSpan.ToString方法(字符串)或使用自定义格式程序.

Than use string formatter to print the formatted time into the label. I think one of the other answers already shows how to do that. Otherwise here are some good references on how to format a TimeSpan instance TimeSpan.ToString Method (String) or using a custom formatter.

var offsetTimeSpan = new System.TimeSpan(0,45,0).Add(ss.Elapsed)

这篇关于在C#中设置秒表程序的开始时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆