简体   繁体   中英

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. 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).

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.

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. This would allow you to format the time using custom format strings . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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