从组合框更改定时器间隔

  • 本文关键字:定时器 组合 c# timer
  • 更新时间 :
  • 英文 :


我有一个组合框中的项目。当我选择项目时,计时器间隔必须乘以组合框中选择的数字。但是当运行代码时,它显示"System。参数outofrangeexception: '值'0'不是Interval的有效值。间隔必须大于0。"组合框中的项分别为1、2、4、8、10和20。

代码在

下面
int x1;
private int ch1xscale()
{
x1 = Convert.ToInt32(cmbch1.SelectedItem);
return x1;
}
timer1.Tick += Timer1_Tick;
timer1.Interval = 100*ch1xscale();

cmbch1.SelectedIndex = 3;

怎么了?

让我给你举个例子。如果您按照这个示例设置代码,它将毫无问题地工作。试着设置interval,不要改变定时器类的其他样例变量。

因为计时器是一个线程,所以我必须使用delegate来同步使用其他控件。

1。创建计时器

Timer timer;
public delegate void InvokeDelegate();
int x1;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Tick += Timer_Tick;
timer.Interval = 100;
timer.Start();
}
private int ch1xscale()
{
x1 = Convert.ToInt32(cmbch1.SelectedItem);
return x1;
}

2。计时器滴答

private void Timer_Tick(object sender, EventArgs e)
{
//do work
this.BeginInvoke(new InvokeDelegate(InvokeMethod));
}
void InvokeMethod()
{
myLabel.Text = timer.Interval.ToString();
}

3.combobox selected changed event

private void cmbTimer_SelectedIndexChanged(object sender, EventArgs e)
{         
timer.Stop();
timer.Interval = 100 * ch1xscale();
timer.Start();           
}

最新更新