button to add one minute [closed]

-4

Hello I have this code and would like to make a button to add a minute to the time that is running.

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;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        private int quick = 1800;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1 = new System.Windows.Forms.Timer();
            timer1.Interval = 1800;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Enabled = true;


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            quick--;
            label1.Text = quick / 60 + " : " + ((quick % 60) >= 10 ? (quick % 60).ToString() : "0" + (quick % 60));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Stop();
        }
    }
}
    
asked by anonymous 16.10.2018 / 15:44

1 answer

0

The interval of your timer is wrong, if you want a synchronization with seconds, you must match this interval, as it is assigned in milliseconds and so that its Tick event is triggered every 1s (decreasing remaining time), you must declare its value as 1000 (1000ms = 1s). Already the display part, it is a bit confusing and with unnecessary operations.

To increase the remaining time, you simply increment the value in the button click, in this case, I added button3 to add 60 seconds.

And finally, you're forgetting to stop your timer after the end of the desired interval.

public partial class Form1 : Form
{
    int tempoRestante = 1800;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1000;
        timer1.Tick += new EventHandler(timer1_Tick);            
        timer1.Enabled = true;
    }

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

    private void timer1_Tick(object sender, EventArgs e)
    {

        if (tempoRestante <= 0)
            timer1.Stop();
        else
            tempoRestante--;

        int minutos = tempoRestante / 60;
        int segundos = tempoRestante % 60;

        label1.Text = string.Format("{0}:{1}", minutos.ToString("#,00"), segundos.ToString("#,00"));

    }

    private void button3_Click(object sender, EventArgs e)
    {
        tempoRestante += 60;

    }
}
    
16.10.2018 / 16:08