【问题标题】:Timer Countdown with progress bar C#带有进度条的计时器倒计时 C#
【发布时间】:2016-03-23 17:29:07
【问题描述】:

我想将项目中的进度条与计时器倒计时同步。

这是我现在拥有的:

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

        private int counter=80;
        DateTime dt = new DateTime();
        private void button1_Click(object sender, EventArgs e)
        {
            int counter = 80;
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000;
            timer1.Start();
            textBox1.Text = counter.ToString();
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            counter--;
            progressBar1.Increment(1);
            if (counter == 0)
            {
                timer1.Stop();
            }
            textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            textBox1.Clear();
            progressBar1.Value = 0;
        }
    }
}

我希望在计时器结束时完成进度条。

【问题讨论】:

  • 呃什么?为什么进度条会基于时间?我也打赌这是因为 GUI 没有被强制更新
  • 我意识到这是一篇旧帖子,但进度条在可视化持续时间方面无处不在,以至于许多用户对基于任务的进度条感到沮丧,该进度条会快速进展到某个点并等待在前进之前的不成比例的时间。用户不关心任务的数量,他们关心需要多长时间。所以你会发现创建一个以时间为中心的进度条,而不是一个以任务为中心的进度条是一个非常普遍的要求,尤其是在移动农场游戏爆炸式增长之后。

标签: c# visual-studio timer progress-bar


【解决方案1】:

您需要指定progressBar1 以使其.StepMaximum 属性与Intervalcounter 变量匹配。例如:

    private int counter = 80;
    DateTime dt = new DateTime();
    private void button1_Click(object sender, EventArgs e)
    {
        // The max is the total number of iterations on the 
        // timer tick by the number interval.
        progressBar1.Max = counter * 1000;
        progressBar1.Step = 1000;

        timer1 = new System.Windows.Forms.Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000;
        timer1.Start();
        textBox1.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;

        // Perform one step...
        progressBar1.PerformStep();

        if (counter == 0)
        {
            timer1.Stop();
        }
        textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
    }

【讨论】:

  • 大卫,如果我想让它与带有文本框的计时器的输入一起工作,你能帮我吗?
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多