2016-04-12 18 views
0

私は、forループを使って複数のタイマーを作成し、タイマーは対応するラベルに表示されます。ボタンをクリックすると "n"回、 "n"回作成されます。このコードは実行時のタイムカウントダウンでエラーを示します。各タイマーは異なる間隔で減分されています。この問題を解決するには?C#windowsアプリケーションフォームで複数のカウントダウンタイマーを作成する方法は?

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(); 

    } 
+0

あなたは私たちに、エラーメッセージを表示することができます:

はこのようなものは、ダウンカウントを表示するラベルの値を使用してみてください?また、タイマー間で 'timesec'を共有しています。また、複数のタイマーを使用して達成したいことを正確に説明することは、おそらく最良のアイデアではありません。 – gzaxx

+0

* One * Timerのみを使用してください。その唯一の仕事はラベルを更新することです。 Intervalプロパティは重要ではありません.45 msecは十分に高速です。タイミングを開始するときに、各ラベルにDateTime.UtcNow値を格納します。そして、DateTime.Utcからそれを減算して、どれくらいの時間が経過したかを知るために更新します。 –

答えて

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(); 
    } 
} 
関連する問題