0

可能重复:
如何在 C# 中启用此计时器?

我试图让一个小项目运行。当我使用断点时,它会正确地通过代码,但是当以正常速度运行程序时,它的序列运行速度太快。我试图让交通灯序列每 1 秒改变一次。这段代码有什么问题?它是一个简单的红绿灯序列,以防您感兴趣:)。新手项目。

    }
        public int counter = 0;

    private void rbStart_CheckedChanged(object sender, EventArgs e)
    {
        Light_timer.Start();
        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;
        Light_timer.Stop();
    }

}

}

4

1 回答 1

3

每次计时器经过时,您都会连接事件处理程序等等......试试这个:

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

private void TimerElapsed(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;
        Light_timer.Stop();
    }
}

private void rbStart_CheckedChanged(object sender, EventArgs e)
{
    Light_timer.Start();
}

private void rbStop_CheckedChanged(object sender, EventArgs e)
{
    Light_timer.Stop();
    pbRed.Visible = false;
    pbAmber.Visible = false;
    pbGreen.Visible = false;
}
于 2012-10-06T23:36:04.753 回答