【发布时间】:2015-08-24 13:01:48
【问题描述】:
我做了一个简单的倒数计时器,但是当我在文本框中输入0 : 0 : 0 时,计时器变为负数-1 : 59 : 59。我尝试输入0 : 0 : 1,计时器停在0 : 0 : 0,消息框出现在屏幕上
我试过这段代码来防止负值,但它停在-1 : 59 : 58
if (label1.Text == "-1")
{
timer1.Stop()
}
试过这段代码,但它停在-1 : 59 : 59
if (h < 0)
{
timer1.Stop();
}
这里是代码
namespace Timer
{
public partial class Form1 : Form
{
int h;
int m;
int s;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
textBox1.Text = "0";
}
if (textBox2.Text == "")
{
textBox2.Text = "0";
}
if (textBox3.Text == "")
{
textBox3.Text = "0";
}
h = Convert.ToInt32(textBox1.Text);
m = Convert.ToInt32(textBox2.Text);
s = Convert.ToInt32(textBox3.Text);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
s = s - 1;
if(s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
if (h == 0 && m == 0 && s == 0)
{
timer1.Stop();
MessageBox.Show("Times up!", "Time");
}
string hh = Convert.ToString(h);
string mm = Convert.ToString(m);
string ss = Convert.ToString(s);
label1.Text = hh;
label2.Text = mm;
label3.Text = ss;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
【问题讨论】:
-
您是否尝试使用调试器查看发生了什么
-
您是否已通过代码查看发生了什么?代码完全按照您的要求执行 - 逐步执行并观察,您会看到。
-
线索 - 错误在刻度处理程序的第一行
-
你为什么不使用 TimeSpan 对象?