显示经过的时间

本文关键字:时间 经过 显示 | 更新日期: 2023-09-27 17:57:12

我需要动态显示经过的时间。我的代码将根据间隔值弹出一条消息。

public void button1_Click(object sender, EventArgs e)
{
    this.TopMost = true;
    DialogResult result1 = MessageBox.Show("Add some notes to your current ticket?",
    "Add Notes",
    MessageBoxButtons.YesNo);

    if (result1 == DialogResult.Yes)
    {
        Timer tm;
        tm = new Timer();
        int minutes = int.Parse(textBox2.Text);
        tm.Interval = (int)TimeSpan.FromMinutes(minutes).TotalMilliseconds;
        tm.Tick += new EventHandler(button1_Click);
        tm.Enabled = true;
        string pastebuffer = DateTime.Now.ToString();
        pastebuffer = "### Edited on " + pastebuffer + " by " + txtUsername.Text + " ###";
        Clipboard.SetText(pastebuffer);
        tm.Start();
    }
    else if (result1 == DialogResult.No)
    { 
    }
    this.TopMost = false;
}

如果我在间隔中定义了 15 分钟,如何让倒计时显示在标签中?

显示经过的时间

您应该

将结束时间存储在表单级别的文件中Tick然后在计时器的事件处理程序中检查结束时间和现在之间的差异,并更新要显示倒数计时器的标签:

private DateTime endTime;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private void button1_Click(object sender, EventArgs e)
{
    var minutes = 0;
    if (int.TryParse(textBox1.Text, out minutes) && timer.Enabled == false)
    {
        endTime = DateTime.Now.AddMinutes(minutes);
        timer.Interval = 1000;
        timer.Tick -= new EventHandler(timer_Tick);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
        UpdateText();
    }
}
void timer_Tick(object sender, EventArgs e)
{
    UpdateText();
}
void UpdateText()
{
    var diff = endTime.Subtract(DateTime.Now);
    if (diff.TotalSeconds > 0)
        label1.Text = string.Format("{0:D2}:{1:D2}:{2:D2}",
                                   diff.Hours, diff.Minutes, diff.Seconds);
    else
    {
        this.Text = "00:00:00";
        timer.Enabled = false;
    }
}

我不会用计时器胡说八道。为此,我会使用Microsoft的响应式框架。只需NuGet "Rx-Winforms"即可获取位。然后你可以这样做:

Observable
    .Create<string>(o =>
    {
        var now = DateTimeOffset.Now;
        var end = now.AddMinutes(15.0);
        return
            Observable
                .Interval(TimeSpan.FromSeconds(0.1))
                .TakeUntil(end)
                .Select(x => end.Subtract(DateTimeOffset.Now).ToString(@"mm':ss"))
                .DistinctUntilChanged()
                .Subscribe(o);
    })
    .ObserveOn(this)
    .Subscribe(x => label1.Text = x);

这将自动创建一个倒数计时器,该计时器将使用以下值更新label1中的文本:

14:5914:5814:5714:5614:5514:54...00:0200:0100:00

如果要在计时器用完之前停止此操作,Subscribe 方法将返回一个IDisposable,您可以将其调用.Dispose()

你应该试着计算15分钟。例如,如果您使用标签(Label1),则应使用计时器对其进行计数。只需使用计时器并计算每个刻度(1000毫秒)+1

Timer1 has a +1 (declare a int as 0)
If the label reaches the number of seconds or minutes
(You can modify that with milliseconds), it stops the timer.