简体   繁体   English

简单的倒数计时器 C# 显示分钟和秒 - 已经有分钟

[英]Simple countdown timer C# showing Minutes and Seconds - already have minutes

I have a Windows form with a simple countdown timer to show viewers how much time is left in a motor race.我有一个 Windows 表单,其中包含一个简单的倒计时计时器,用于向观众显示赛车比赛还剩多少时间。 It works for showing how many minutes are left, but I need it to show how many minutes and seconds are left.它用于显示还剩多少分钟,但我需要它来显示还剩多少分钟和秒。

The user can decide whether to show the time or not (as a label in front of a picturebox), and user can start/stop/reset/add or subtract minutes (all user entry is in minutes).用户可以决定是否显示时间(如图片框前的 label),用户可以开始/停止/重置/增加或减少分钟(所有用户输入以分钟为单位)。

I would appreciate it if someone could give me a pointer on how to format the time remaining to show as 000:00 (ie mmm:ss) and to count down in seconds.如果有人能给我一个关于如何格式化剩余时间以显示为 000:00(即 mmm:ss)并以秒为单位倒计时的指示,我将不胜感激。

This is what I have so far:这是我到目前为止所拥有的:

int timeleft = 10;
private void timer1_Tick(object sender, EventArgs e)
{
    if (timeleft > 0)
    {
        timeleft = timeleft - 1;
        label3.Text = timeleft + " Mins";
    }
    else
    {
        timer1.Stop();
        label3.Text = "Time Up";
    }
}

private void button26_Click(object sender, EventArgs e)
{
    timer1.Start();
}

private void button27_Click(object sender, EventArgs e)
{
    timer1.Stop();
}

private void button32_Click(object sender, EventArgs e)
{
    timer1.Stop();
    timeleft = 20;
    label3.Text = timeleft + " Mins";
}

private void button28_Click(object sender, EventArgs e)
{
    timeleft = timeleft + 1;
    label3.Text = timeleft.ToString() + " Mins";
}

private void button30_Click(object sender, EventArgs e)
{
    timeleft = timeleft - 1;
    label3.Text = timeleft.ToString() + " Mins";
}

private void button7_Click(object sender, EventArgs e)
{
    timeleft = timeleft + 10;
    label3.Text = timeleft.ToString() + " Mins";
}

private void button29_Click(object sender, EventArgs e)
{
    label3.BringToFront();
}

You should be using a TimeSpan to describe the time left.您应该使用TimeSpan来描述剩余时间。 This would allow you to format the time using custom format strings .这将允许您使用自定义格式字符串来格式化时间。 Ie IE

timeleft = TimeSpan.FromMinutes(20);
label3.Text = timeLeft.ToString("mm\\:ss");

You could also create an additional extension method that prints either minutes or seconds, depending on the remaining time.您还可以创建一个额外的扩展方法,根据剩余时间打印分钟或秒。 Ie if more than one minute, show only minutes, otherwise show seconds.即如果超过一分钟,只显示分钟,否则显示秒。 Or show both minutes and seconds if less than 5 minutes but more than 1 minute remaining.或者,如果剩余时间少于 5 分钟但多于 1 分钟,则同时显示分钟和秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM