让这个计时器在C#中工作(新手)

时间:2012-10-06 23:07:22

标签: c# timer intervals

  

可能重复:
  How do I enable this timer in 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();
    }

}

}

1 个答案:

答案 0 :(得分: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;
}