Windows 表单计时器运行不稳定
Windows Forms timer runs erratically
我正在尝试通过计时器控制进度条 - 也就是说,让进度条在每个 timer_Tick 时前进其最大值的 10%。奇怪的是,虽然进度条似乎确实随着 timer_Tick 前进,但似乎每个滴答声都是成对出现的(也就是说,我得到了两次滴答声)。这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ExampleTestGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = false; //Set to false to prevent timer from auto-starting.
timer1.Interval = 1000;
progressBar1.Maximum = 10;
}
// COMBO BOX
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
// START BUTTON
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "CANCEL TEST";
comboBox1.Enabled = false;
timer1.Start();
timer1.Tick += new EventHandler(timer1_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value != 10)
{
progressBar1.Value++;
}
else
{
timer1.Stop();
button1.Text = "START AGAIN";
comboBox1.Enabled = true;
progressBar1.Value = 0;
}
}
}
}
timer1.Start
只依赖于button1_Click
。有没有人经历过这种奇怪的行为?我的代码中有菜鸟错误吗?
只添加一次处理程序。将此行移至窗体的构造函数:
timer1.Tick += new EventHandler(timer1_Tick);
或者如果您已经使用设计器创建了 tick 事件,则完全删除该行。
我正在尝试通过计时器控制进度条 - 也就是说,让进度条在每个 timer_Tick 时前进其最大值的 10%。奇怪的是,虽然进度条似乎确实随着 timer_Tick 前进,但似乎每个滴答声都是成对出现的(也就是说,我得到了两次滴答声)。这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ExampleTestGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = false; //Set to false to prevent timer from auto-starting.
timer1.Interval = 1000;
progressBar1.Maximum = 10;
}
// COMBO BOX
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
// START BUTTON
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "CANCEL TEST";
comboBox1.Enabled = false;
timer1.Start();
timer1.Tick += new EventHandler(timer1_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value != 10)
{
progressBar1.Value++;
}
else
{
timer1.Stop();
button1.Text = "START AGAIN";
comboBox1.Enabled = true;
progressBar1.Value = 0;
}
}
}
}
timer1.Start
只依赖于button1_Click
。有没有人经历过这种奇怪的行为?我的代码中有菜鸟错误吗?
只添加一次处理程序。将此行移至窗体的构造函数:
timer1.Tick += new EventHandler(timer1_Tick);
或者如果您已经使用设计器创建了 tick 事件,则完全删除该行。