日期:2014-05-18  浏览次数:21073 次

c# Timer问题
问题:C#程序,以下代码第一次按按钮是正常的,比如说TextBox1里输入5,TextBox1里的值是每秒减1的,但是第二次再输数字就变成每秒减2了,第三次是每秒减3了。为什么会这样,该怎么改?
  private void button7_Click(object sender, EventArgs e)
  {
  try
  {
  if (textBox1.Text == "")
  {
  throw new FormatException("please input time");
  }
  timeleft = int.Parse(textBox1.Text);
  timer1.Enabled = true;
  timer2.Enabled = true;
  timer1.Tick += new EventHandler(timer1_Tick);
  timer2.Tick += new EventHandler(timer2_Tick);
  timer1.Interval = timeleft * 1000;
  timer2.Interval = 1 * 1000;
  //timer1.Interval = timeleft * 60 * 1000;
  //timer2.Interval = 1 * 60 * 1000;
  timer1.Start();
  timer2.Start();  
  }
  catch (FormatException fEx)
  {
  MessageBox.Show(fEx.Message);
  }
  }

  private void timer1_Tick(object sender, EventArgs e)
  {
  timer1.Enabled = false;
  timer2.Enabled = false;
  MessageBox.Show("time is up"); 
  }

  private void timer2_Tick(object sender, EventArgs e)
  {
  timeleft--;
  textBox1.Text = timeleft.ToString();
  }

------解决方案--------------------
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Tick += new EventHandler(timer2_Tick);
看见这两行了吗,你点击一次按钮,就多绑定一次,这样就会多次绑定,本来timer5秒一次,这样就可能5秒多次了,把绑定事件放到外面去,初始化绑定一次就好了,不要每次点击都绑定
------解决方案--------------------
因为你每次点击按钮的时候,都进行了事件绑定
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Tick += new EventHandler(timer2_Tick);