我想知道如何创建一个sum + 1每 5 秒添加一次的标签?我尝试过使用 if 循环,但不幸的是它在一秒钟后重置。
using System.Diagnostics;
// using system.diagnotics voor stopwatch
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Stopwatch sw = new Stopwatch();
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
sw.Start();
if (timer1.Enabled == true) { button1.Text = "stop"; }
else { button1.Text = "false"; sw.Stop(); }
}
private void timer1_Tick(object sender, EventArgs e)
{
int hours = sw.Elapsed.Hours;
int minutes = sw.Elapsed.Minutes;
int seconds = sw.Elapsed.Seconds;
int sum = 0;
label1.Text = hours + ":" ;
if (minutes < 10) { label1.Text += "0" + minutes + ":"; }
else { label1.Text += minutes + ":"; }
if (seconds < 10) { label1.Text += "0" + seconds ; }
else { label1.Text += seconds ; }
if (seconds ==5) { sum = sum +=1; }
label2.Text = Convert.ToString(sum);
}
}
}
Run Code Online (Sandbox Code Playgroud)
sum应该是一个类字段。您还可以使用自定义格式字符串来表示经过的时间跨度。
int sum = 0;
private void timer1_Tick(object sender, EventArgs e)
{
// int sum = 0; local variable will be set to zero on each timer tick
label1.Text = sw.Elapsed.ToString(@"hh\:mm\:ss");
// btw this will not update sum each five seconds
if (sw.Elapsed.Seconds == 5)
sum++; // same as sum = sum +=1;
label2.Text = sum.ToString();
}
Run Code Online (Sandbox Code Playgroud)
仅当当前已用超时的第二个值为 5 时,当前的实现才会增加总和。这永远不会发生(取决于你的计时器间隔)。如果您将计时器间隔设置为 1000 毫秒,那么您可以增加每个刻度的总和,但设置label2.Text = (sum % 5).ToString()。