[英]How do I enable this timer in C#?
I've started a course of c# and I cant get my timer to run. 我已经开始了C#课程,但无法运行计时器。 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. 我想要间隔1秒。 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;
}
} }
The Interval property merely designates how much time elapses between Tick events. Interval属性仅指定Tick事件之间经过的时间。 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. 然后,只需调整您的UI元素即可反映交通灯的正确状态。 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. 祝好运。
I think you probably misinterpreted how the Timer works. 我认为您可能误解了计时器的工作原理。 The Timer.Tick Event fires when the Interval has elapsed. 间隔过去后,将触发Timer.Tick事件 。 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. 实际上,System.Windows.Forms.Timer无法检索经过的时间,这意味着您需要一种不依赖于此的状态跟踪机制。 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. 仔细看一下我在上面引用的页面上的示例,并确保您了解它的工作原理,然后再进行尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.