簡體   English   中英

如何使時間計數器從當前點而不是從開始繼續向上/向下?

[英]How can I make the time counter to continue up/down from the current point and not from the start?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Extract
{
    public partial class TimeCounter : Label
    {
        public bool CountUp { get; set; }

        private Timer _timer;
        private int _elapsedSeconds;
        private TimeSpan ts = TimeSpan.FromSeconds(100);

        public TimeCounter()
        {
            InitializeComponent();

            StartCountDownTimer();
        }

        public void StartCountDownTimer()
        {
            _timer = new Timer
            {
                Interval = 1000,
                Enabled = true
            };
            _timer.Tick += (sender, args) =>
            {
                if (CountUp == false)
                {
                    ts = ts.Subtract(TimeSpan.FromSeconds(1));
                    this.Text = ts.ToString();
                }
                else
                {
                    _elapsedSeconds++;
                    TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
                    this.Text = time.ToString(@"hh\:mm\:ss");
                }
            };
        }

        private void TimeCounter_Load(object sender, EventArgs e)
        {

        }
    }
}

在form1中

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked)
            {
                timeCounter1.CountUp = true;
            }
            else
            {
                timeCounter1.CountUp = false;
            }
        }

當我在 form1 中更改 CountUp 標志時,它會向上/向下更改時間計數器方向,但每次都會重新開始。 Id 它正在計數,然后從 00:00:00 開始,如果倒計時,則從 1 分 40 秒 00:01:40

當我更改標志時,我怎樣才能做到這一點,它會從當前時間而不是從一開始就改變方向?

例如,如果時間是 00:00:13(向上計數)並且我將標志更改為向下計數,則從 00:00:13 ... 00:00:12 向下計數...如果正在計數,則以另一種方式進行計數向下,我將其更改為向上計數,然后從當前時間繼續向上。

你需要“_elapsedSeconds”做什么?

就用?

_timer.Tick += (sender, args) =>
{
    if (CountUp)
    {
        ts = ts.Add(TimeSpan.FromSeconds(1));        
    }
    else
    {
        ts = ts.Subtract(TimeSpan.FromSeconds(1));            
    }
    this.Text = ts.ToString();
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM