交通灯计划使用计时器

时间:2014-08-02 20:23:30

标签: vb.net

我正在尝试进行简单的红绿灯模拟,我希望它是这样的情况,当我按下一个按钮时,序列开始,每五秒就有一个颜色变化。我正在使用三个面板。

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Panel1.BackColor = Color.White

我知道这是你为1个事件设置它的方式,但是在我的程序中,顶部面板以红色开始,另外两个为白色,五秒后我希望第二个面板变为黄色,再经过五秒钟后,我希望前两个面板变为白色,第三个面板变为绿色。我怎么做到这一点?另外,如何在单击按钮时启动该过程?

1 个答案:

答案 0 :(得分:1)

所以我做的是制作一个名为LightStatus的Enum,它会使当前点亮的灯光变量(lsCurrent)在代码中更具可读性。

当表单加载时,它会以5000毫秒的间隔设置计时器属性,因此它将每5秒触发一次Elapsed事件。我在触发器的Elapsed事件中添加一个处理程序来调用ChangeLight Sub。它还将Red传递给SetLight,以便Red立即点亮。

单击该按钮时,将启动计时器。当Elapsed事件被触发时,它运行ChangeLight,它将lsCurrent从绿色变为黄色,黄色变为红色或红色变为绿色,并调用SetLight,它根据lsCurrent设置Panel BackColor。

Public Class Form1

Dim tmrLight As System.Timers.Timer = New System.Timers.Timer
Dim lsCurrent As LightStatus = LightStatus.Red

Private Enum LightStatus
    Red = 1
    Yellow = 2
    Green = 3
End Enum

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

    tmrLight.Interval = 5000
    AddHandler tmrLight.Elapsed, AddressOf ChangeLight
    SetLight(LightStatus.Red)

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    tmrLight.Start()

End Sub

Private Sub ChangeLight()

    Select Case lsCurrent

        Case LightStatus.Red

            lsCurrent = LightStatus.Green

        Case LightStatus.Yellow

            lsCurrent = LightStatus.Red

        Case LightStatus.Green

            lsCurrent = LightStatus.Yellow

        Case Else

            lsCurrent = LightStatus.Red

    End Select

    SetLight(lsCurrent)

End Sub

Private Sub SetLight(LightColor As LightStatus)

    Select Case LightColor

        Case LightStatus.Red

            Me.pnlRed.BackColor = Color.Red
            Me.pnlYellow.BackColor = Color.White
            Me.pnlGreen.BackColor = Color.White

        Case LightStatus.Yellow

            Me.pnlRed.BackColor = Color.White
            Me.pnlYellow.BackColor = Color.Yellow
            Me.pnlGreen.BackColor = Color.White

        Case LightStatus.Green

            Me.pnlRed.BackColor = Color.White
            Me.pnlYellow.BackColor = Color.White
            Me.pnlGreen.BackColor = Color.Green

        Case Else

            Me.pnlRed.BackColor = Color.Red
            Me.pnlYellow.BackColor = Color.White
            Me.pnlGreen.BackColor = Color.White

    End Select

End Sub

End Class