如何在固定时间内更改按钮的backColor?

时间:2018-08-29 14:11:11

标签: c# timer

当某个值来自串行端口时,我想在固定时间内更改BackColor中的Button。我在这里设置Timer对象:

public formLabel()
{
    InitializeComponent();
    // ...
    timerColor.Tick += timerColor_Tick;
    timerColor.Interval = 3000;
}

然后,当我从串行端口接收信号时:

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    MessageBox.Show("Dati Ricevuti: " + indata);
    if (indata.CompareTo("K") == 0)
    {
        timerColor.Enabled = true;
        btnEsito.BackColor = Color.Green;
        btnEsito.Text = "GOOD";
        // Do something
    }
    if (indata.CompareTo("O") == 0)
    {
        timerColor.Enabled = true;
        btnEsito.BackColor = Color.Red;
        btnEsito.Text = "NO GOOD";
    }
}

这是停止计时器的方法:

private void timerColor_Tick(object sender, EventArgs e)
{
    MessageBox.Show("HERE!");
    timerColor.Enabled = false;
    btnEsito.BackColor = Color.White;
}
根据我收到的信号类型,BackColor中的

btnEsito变为绿色或红色,但是程序未显示消息"HERE!",并且按钮没有返回白色

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

System.Windows.Forms.Timer专为单线程使用而设计,需要在UI线程上启动和停止。您试图在单独的线程上启动计时器,因此需要确保在UI线程上完成了对timer Enabled属性的修改。您可以通过创建一个委托方法并从事件处理程序中调用它来完成此操作-可能是这样的:

delegate void TimerDelegate(bool Enable);
private void ControlTimer(bool Enable)
{
  timerColor.Enabled = Enable;
}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    MessageBox.Show("Dati Ricevuti: " + indata);
    if (indata.CompareTo("K") == 0)
    {
        Invoke((TimerDelegate)ControlTimer, true);
        btnEsito.BackColor = Color.Green;
        btnEsito.Text = "GOOD";
        // Do something
    }
    if (indata.CompareTo("O") == 0)
    {
        Invoke((TimerDelegate)ControlTimer, true);
        btnEsito.BackColor = Color.Red;
        btnEsito.Text = "NO GOOD";
    }
}

private void timerColor_Tick(object sender, EventArgs e)
{
    MessageBox.Show("HERE!");
    Invoke((TimerDelegate)ControlTimer, false);
    btnEsito.BackColor = Color.White;
}