计时器和按钮问题

Timer and Buttons Issues

我正在使用 Visual Studio 2013 使用 C# 做一个项目。我想让计时器从 120 分钟倒计时到 0 分钟,当它倒计时到 0 时,一个消息框会显示时间到了。我还希望在按下重置按钮时重置计时器。但是,当我按下重置按钮时,即使计时器已重置,我按下开始按钮,也会出现消息框 "Time's up",计时器不会启动。请帮我。我是 C# 的新手,所以请尽量不要给我难以理解的复杂答案。另外,你会经常看到我,因为我会有更多问题要问。谢谢!! (这是我的代码。)

    private void startbutton_Click(object sender, EventArgs e)
    {
        timer.Enabled = true;
        foreach (var button in Controls.OfType<Button>())
        {
            button.Click += button_Click;
            timer.Start();
            button.BackColor = Color.DeepSkyBlue;
        }
    }

    private void stopandresetbutton_Click(object sender, EventArgs e)
    {
        button.BackColor = default(Color);
        timer.Stop();
        timeleft = 0;
        timerlabel.Hide();
    }

    int timeleft = 120;
    private void timer_Tick(object sender, EventArgs e)
    {
        if (timeleft > -1)
        {
            timerlabel.Text = timeleft + " minutes";
            timeleft = timeleft - 1;
        }
        else
        {
            timer.Stop();
            MessageBox.Show("Time's up!");
        }
    }

您的错误在 stopandresetbutton_Click 方法。你不应该将 timeLeft 变量设置为 0。因为你想重置 计时器,你应该将它设置为 120(如果你的单位是分钟)。

您在 startbutton_Click 方法中将 timeLeft 变量设置为 120。这样它也可以工作

为了更好的方法

你可以这样写属性

private int TimeLeft {
    get {return timeLeft; }
    set {
        timeLeft = value;
        timerlabel.Text = timeleft + " minutes";
    }
}

这样您就可以将 TimeLeft 设置为某个值,标签的文本也会随之改变。这是因为您可能不记得在设置 timeLeft 值后更改标签的文本。