C# 当计时器达到零时停止计时器
当计时器为零时,如何停止计时? 我在这里有此windows窗体代码:C# 当计时器达到零时停止计时器,c#,winforms,timer,C#,Winforms,Timer,当计时器为零时,如何停止计时? 我在这里有此windows窗体代码: 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; u
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();
}
我不确定这是否可行,但我认为它会:
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]
}
}
请听我的评论。您可以将计时器代码更改为此。它将从显示初始值开始
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);
}
您正在初始化类作用域
seconds
字段,但此后从未为其赋值。这意味着您的if
语句的计算结果总是相同的,并且永远不会达到条件。我想你忘了写一行代码,其中countdown
被指定为seconds
或类似的内容。虽然这项任务似乎没有必要,而且您应该能够在if
语句中计算countdown
。您能否在此提供一个关于如何实现它的示例代码?我对这个windows窗体项目和计时器也很陌生。将if(seconds>0)
更改为if(countdown.TotalSeconds>0)
。您正在评估是否还有第二秒的停机时间。您的秒数
从未减少。该条件有效,先生,谢谢。但是在1秒后的时间“0:1”中,它将显示“Times Up!”。当计时器达到“0:0”时,如何更改它?文本显示“Times Up!”。这是您需要的另一个循环,因此如果(countdowntime.TotalSeconds>=0)更改为。顺便说一句,如果你觉得答案有用,你可以投票。谢谢