简体   繁体   中英

C# Visual Studio Form, Can't Reset Timer

Dispose isn't working in my code for some reason. When i hit the reset button, and then start again, it won't start the timer over. I've tried disabling and reenablinig enabled(), but it still didn't work.

Here's my code:

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 WindowsFormsApp1
{
    public partial class StopWatch : Form
    {
        bool reSet = false;
        bool stopped = true;
        public StopWatch()
        {
            InitializeComponent();
        }

        private void startStop_Click(object sender, EventArgs e)
        {

            timer1.Enabled = true;
            if (stopped == true)
            {
                timer1.Start();
                stopped = false;
            }
            else
            {
                timer1.Stop();
                stopped = true;
            }

        }

        private void reset_Click(object sender, EventArgs e)
        {
            timer1.Dispose();
            txtBox.Text = "";
            reSet = true;
            stopped = true;

        }
        int i = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            txtBox.Text = i.ToString();
            i++;
        }
    }
}

Forget the timer for now, just make a stopwatch:

DateTime startTime = DateTime.MinValue; //it's reset

StartButton_Click(...){
  startTime = DateTime.Now;
}

StopButton_Click(...){
  MessageBox.Show("counted secs: " + (DateTime.Now - startTime).TotalSeconds);
}

That's a stopwatch

Now let's make it look like it runs. Add a label to the Form. Add a timer to the form, set it's interval to 100, enable it and put a tick event:

Timer_Tick(...){
  StopWatchLabel.Text = startTime == DateTime.MinValue ? "00:00:00.000" : (DateTime.Now - startTime).ToString();
}

Now you can get into the minutiae of adding a reset button (set startTime to MinValue) starting and stopping the timer (no point updating a label to 00:00 ten times a second, but no harm in it either) but hopefully this proves that the timer is not (and should not) be part of the stopwatch function of measuring the passage of time. The timer doesn't need messing with/disposing etc. It's purely to update a label with the period that has passed since your start time

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