如何在达到零时停止计时器? 我在这里有这个窗体表格代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace SoftwareEngineering
{
public partial class MainGame : Form
{
int minutes = 2;
int seconds = 0;
private TimeSpan countdowntime;
public MainGame()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void NewGame_Click(object sender, EventArgs e)
{
setcountdown(minutes, seconds);
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan tSecond = new TimeSpan(0, 0, 1);
countdowntime = countdowntime.Subtract(tSecond);
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}
}
private void setcountdown(int min,int sec)
{
TimeSpan temp = new TimeSpan(0 , min , sec);
countdowntime = temp;
}
代码有效但一旦达到“0:0”,它将继续递减到“0:-1”等等,我的条件在停止计时器时似乎不起作用。
这是我的上述条件:
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}
答案 0 :(得分:1)
根据我的意见。您可以将计时器代码更改为此。它将从显示您的初始值
开始private void timer1_Tick(object sender, EventArgs e)
{
//I've edited you're code if(countdowntime.TotalSeconds > 0)
//to this because @ "0:1" It will display Times Up
if (countdowntime.TotalSeconds >= 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!\r\n";
timer1.Stop();
return;
}
TimeSpan tSecond = new TimeSpan(0, 0, 1);
countdowntime = countdowntime.Subtract(tSecond);
}
答案 1 :(得分:0)
我不确定这会有效,但我认为它会:
private void timer1_Tick_1(object sender, EventArgs e)
{
counter--; [COLOR=#006400]//Decrease the counter, just like the timer decreases.[/COLOR]
if (counter == 0) [COLOR=#006400]//If we hit 0, or any other number we'd like to check.[/COLOR]
{
MessageBox.Show("Time Up!");
counter = timer.Interval;[COLOR=#006400]//Reset the counter.[/COLOR]
timer.Start();[COLOR=#006400]//Re-start the timer.[/COLOR]
}
}