How do I enable this timer in C#?

一个人想着一个人 提交于 2019-12-20 06:07:03

问题


I've started a course of c# and I cant get my timer to run. Its probably pretty simple and I've just missed something here. Basically I have a button to start and stop a traffic light sequence. I wanted an interval of 1 second. Heres what I've written. It doesn't work as intended when I press start. Thank you.

 }
    public int counter = 0;

private void rbStart_CheckedChanged(object sender, EventArgs e)
{

    counter++;

    if (counter == 1)
    {
        pbRed.Visible = true;
        pbAmber.Visible = false;
        pbGreen.Visible = false;
    }
    else if (counter == 2)
    {
        pbRed.Visible = true;
        pbAmber.Visible = true;
        pbGreen.Visible = false;
    }
    else if (counter == 3)
    {
        pbRed.Visible = false;
        pbAmber.Visible = false;
        pbGreen.Visible = true;
    }
    else if (counter == 4)
    {
        pbRed.Visible = false;
        pbAmber.Visible = true;
        pbGreen.Visible = false;
    }
    else if (counter == 5)
    {
        pbRed.Visible = true;
        pbAmber.Visible = false;
        pbGreen.Visible = false;
    }
    else
    {
        counter = 0;
    }
}

private void rbStop_CheckedChanged(object sender, EventArgs e)
{

    pbRed.Visible = false;
    pbAmber.Visible = false;
    pbGreen.Visible = false;
}

private void Form1_Load(object sender, EventArgs e)
{
    Light_timer.Tick += new EventHandler(rbStart_CheckedChanged);
    Light_timer.Interval = 1000;

}

}


回答1:


The Interval property merely designates how much time elapses between Tick events. You might want to consider a separate variable to track the "state" of your light, and then "bump" that variable with each "Tick" in your event handler. Then just adjust your UI elements to reflect the proper state of your traffic light. You might have a "stopped" state, a "careful" state, and a "green" state, and your light might just "cycle" between each on on each tick. I'll leave you to write the details as it appears to be an assignment. Good luck.




回答2:


I think you probably misinterpreted how the Timer works. The Timer.Tick Event fires when the Interval has elapsed. Interval is used by the Timer to determine how long to run between ticks. Its value is never changed by the Timer. In fact, a System.Windows.Forms.Timer has no way to retrieve elapsed time, which means you'll need a state tracking mechanism of your own that doesn't depend on that. Take a good look at the example on the page I referenced above and make sure you understand how it works, then give it another shot.



来源:https://stackoverflow.com/questions/12755115/how-do-i-enable-this-timer-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!