如何让用户输入一个整数并基于该值启动计时器

本文关键字:整数 一个 于该值 计时器 启动 用户 输入 | 更新日期: 2023-09-27 18:13:06

我正在创建我的第一个c#项目,一个个人时间跟踪应用程序。到目前为止,非常基本,但在我得到任何进一步之前,我想让计时器正常工作。

到目前为止,计时器将启动/停止并重置。然而,我想做的一件奇怪的事情是,让用户设置一个时间,并从那里开始计数。

如果他们想从20分钟开始计时,那么它就会

example: 00:20:00将从20开始计数并相加。

然而,到目前为止我还没有弄清楚。

代码如下:

namespace TimeTracker
{
    public partial class Form1 : Form
    {
    public Form1()
    {
      InitializeComponent();
      TimerBox.Text = string.Format("00:00:00");
    }
    int ss = 0;
    public void StartButton_click(object sender, EventArgs e)
    {
      timer1.Start();
      timer1.Enabled = true;
      timer1.Interval = 1000;
    }
    public void StopButton_click(object sender, EventArgs e)
    {
      timer1.Stop();
      TimerBox.Text = TimeSpan.FromSeconds(ss).ToString(); 
    }
    public void ResetButton_click(object sender, EventArgs e)
    {
      ss = 0;
      TimerBox.Text = TimeSpan.FromSeconds(ss).ToString();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
      ss++;
      TimerBox.Text = TimeSpan.FromSeconds(ss).ToString(); 
    }
  }
}

程序如下:

https://i.stack.imgur.com/wquBP.jpg

任何帮助将不胜感激,我可以提供更多的细节,如果你愿意!

编辑:由于不清楚,我的问题是:

什么过程会更好地编码这个,添加到整数,或者如果有一个更好的方法来实现这一点?

如何让用户输入一个整数并基于该值启动计时器

您可以将该ss变量的初始值设置为用户输入的任何预定义整数,例如

DateTime _dt = DateTime.Parse(TimertBox.Text);
int ss = _dt.Second + _dt.Minute * 60 + _dt.Hour * 3600;

试试…

public partial class Form1 : Form
{
    private TimeSpan Offset = new TimeSpan();
    private System.Diagnostics.Stopwatch SW = new System.Diagnostics.Stopwatch();
    public Form1()
    {
        InitializeComponent();
        timer1.Interval = 1000;
        UpdateTime();
    }
    public void StartButton_click(object sender, EventArgs e)
    {
        TimeSpan TS;
        if (TimeSpan.TryParse(TimerBox.Text, out TS))
        {
            Offset = TS;
        }
        else
        {
            MessageBox.Show("Invalid Starting Time. Resetting to Zero");
            Offset = new TimeSpan();
        }
        SW.Restart();
        UpdateTime();
        timer1.Start();
    }
    public void StopButton_click(object sender, EventArgs e)
    {
        SW.Stop();
        timer1.Stop();
    }
    public void ResetButton_click(object sender, EventArgs e)
    {
        Offset = new TimeSpan();
        if (SW.IsRunning)
        {
            SW.Restart();
        }
        else
        {
            SW.Reset();
        }
        UpdateTime();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        UpdateTime();   
    }
    private void UpdateTime()
    {
        TimerBox.Text = Offset.Add(SW.Elapsed).ToString(@"hh':mm':ss");
    }
}

尝试正常使用计时器(从00:00:00.00开始),当更新输出标签/文本框等时,只需添加用户写入的时间