c# - 组合框的定时器间隔更改
问题描述
我在组合框中有项目。当我选择该项目时,计时器间隔必须乘以组合框中选择的数字。但是当运行代码时,它会显示“System.ArgumentOutOfRangeException:'Value'0' 不是 Interval 的有效值。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
并且不要更改计时器类的其他示例变量。
仅仅因为计时器是一个线程,我不得不使用 adelegate
来同步以使用其他控件。
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选中改变事件
private void cmbTimer_SelectedIndexChanged(object sender, EventArgs e)
{
timer.Stop();
timer.Interval = 100 * ch1xscale();
timer.Start();
}
推荐阅读
- deep-learning - 用于二分类的 Face_Recognition
- javascript - 如何检查按钮是否在onClick函数内被点击?
- angular - 如何在角度的rxjs可观察数组中添加项目
- javascript - axios 500 内部服务器错误后代码执行停止
- arguments - 如何在 SWI-PL 命令行参数中包含双引号?
- xml - 捕获异步 XML 异常
- c# - How to add image or background image to custom button in winforms?
- python - 将 <= 或 == 或 >== 分配给变量 python django
- vue.js - 如何设置 nginx 来解决静态文件 vue 上找不到 404?
- node.js - 如何在字段线图firebase [nodejs] [js]中放置一个变量