定时器刷新表单

时间:2015-11-19 14:59:09

标签: c#

我有一个表单,我想每x秒更新一次。 为了设置我想要的秒,我使用了一个60,120,180,240和300的组合框 这应该确定秒。 计时器正在运行,没有问题。 但是......我不能设定计时器来读取必须运行的秒数。并且,当计时器命中秒时,它应该重新启动,这也是一个问题。 我在c#中非常新,上课等,但这是我无法弄清楚的。 (抱歉我的英语不好)。 我可以在这里得到一些帮助吗? 这就是我的软化。

_ticks++;
label1.Text = _ticks.ToString();
if (_ticks == 10)
{
    label1.Text = "Done";
}

这就是我填写组合的方式

this.cmbRefresh.Items.AddRange(new object[] { "OFF", "60", "120", "180", "240", "300" });

我知道我没有多少,但我不知道从哪里开始。 提前谢谢

4 个答案:

答案 0 :(得分:0)

Handle the ComboBox.SelectedIndexChanged event.您可以通过选择ComboBox,单击F4 for Properties,切换到Events选项卡并双击SelectedIndexChanged事件来实现。

在处理程序中使用int.Parse(this.comboBox1.SelectedItem.ToString())获取秒数并将其乘以一千,并使用this.timer1.Interval = sec * 1000更新间隔。

处理" OFF"在解析为if之前使用int单独评估,因为int.Parse无法使用它。

答案 1 :(得分:0)

您可以使用计时器:

Timer timer = new Timer;
timer.Elapsed += OnTimerEvent;

计时器事件回调:

void OnTimerEvent(Object source, ElapsedEventArgs e)
{
    // Refresh
}

然后,当用户更改组合框时,启动计时器

string t = cmbRefrest.SelectedItem.ToString();
if ("OFF" == t) timer.Enabled = false;
else {
    int timeout = Int32.Parse(t) * 1000;
    timer.Interval = timeout;
    timer.Enabled = true;
}

答案 2 :(得分:0)

所以我想你希望每次更改ComboBox时都要更新它,为此你可以简单地为“SelectedIndexChanged”事件创建一个事件处理程序。

private void cmbRefresh_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbRefresh.Text != "OFF")//If the combobox text is not "OFF"
    {
        timer1.Interval = int.Parse(cmbRefresh.Text) * 1000;//Set the interval to x seconds (value is multiplied by 1000 because timer intervals are set to milliseconds).
    }
    else//If the combobox text is "OFF"
    {
        timer1.Enabled = false;//Stop the timer.
    }
}

答案 3 :(得分:0)

使用Timer上的interval属性并处理Timer.Tick和ComboBox SelectedIndexChanged事件以更新标签。间隔是计时器在提升其Tick事件之前等待的时间量(以毫秒为单位)。

您需要在此处添加逻辑以确保该值为整数。

组合变化:

timer.Interval = Convert.ToInt32(this.cmbRefresh.SelectedValue) * 1000;

处理Tick并安全更新标签。

private void timer_Tick(object sender, EventArgs e)
    {
        var thisTimer = sender as Timer;
        if (thisTimer != null)
        {
            _ticks++;
            this.UpdateLabel(_ticks.ToString());
            if (_ticks == 10)
            {
                this.UpdateLabel("Done");
            }                
        }
    }

private void UpdateLabel(string text)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(() => this.UpdateLabel(text));
    }
    else
    {
        this.label1.Text = text;
    }
}