如何在c#windows应用程序表单中创建多个倒计时器?

时间:2016-04-12 07:11:42

标签: c# winforms

我使用for循环创建了多个计时器,计时器显示在相应的标签中。如果我点击按钮" n"然后" n"将创建时间。此代码显示运行时期间的倒计时错误。每个计时器都会按不同的间隔递减。如何解决这个问题?

    public Dictionary<Timer, Label> dict = new Dictionary<Timer, Label>();

    int n = 1;
    int timesec = 10;
    private void CreateTimers()
    {                        
        for (int i = 1; i <= n; i++)
        {

            Timer timer = new Timer();
            timer = new System.Windows.Forms.Timer();


            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = (1000);//1 sec

            Label label = new Label();
            label.Name = "label" + i;
            label.Location = new Point(0, 100 + i * 30);
            label.TabIndex = i;
            label.Visible = true;

            this.Controls.Add(label);

            dict[timer] = label;

            timer.Enabled = true;
            timer.Start();

        }

     private void button2_Click(object sender, EventArgs e)
    {
        //function call
        CreateTimers();
         n++;
     }
    private void timer_Tick(object sender, EventArgs e)
    { 
       //timer countdown
        Timer t = (Timer)sender;
        timesec--;
        if (timesec == 0)
            t.Stop();
        dict[t].Text = timesec.ToString();

    }

1 个答案:

答案 0 :(得分:0)

有几个问题。首先,您必须消除该循环,因为这会产生比您可能意识到的更多的计时器。此外,由于您希望每个计时器都是独立的,因此您无法更改timesec值。

尝试使用标签的值来显示倒计时,如下所示:

private void CreateTimer() {
  System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
  timer.Tick += timer_Tick;
  timer.Interval = (1000);//1 sec

  Label label = new Label();
  label.Name = "label" + n.ToString();
  label.Text = timesec.ToString();
  label.Location = new Point(0, 100 + n * 30);
  label.Visible = true;
  this.Controls.Add(label);

  dict.Add(timer, label);
  timer.Enabled = true;
  timer.Start();
  n++;
}

private void timer_Tick(object sender, EventArgs e) {
  System.Windows.Forms.Timer t = (System.Windows.Forms.Timer)sender;
  Label l = dict[t];
  int labelTime = 0;
  if (Int32.TryParse(l.Text, out labelTime)) {
    labelTime -= 1;
  }
  l.Text = labelTime.ToString();
  if (labelTime == 0) {
    t.Stop();
  }
}