Ian Lundberg
Ian Lundberg

Reputation: 1883

how to make a timer restart?

i have code that reads from a file and streams it through a label. but when i uncheck the checkbox and check it again it just picks up from where it left off

this is my code

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked == true)
        {
            timer1.Enabled = true;
            timer1.Start();
        }
        else
        {
            timer1.Enabled = false;
        }
    }
    private int start = 0;
    private string lyricspath = @"lyrics.txt";
    private void timer1_Tick(object sender, EventArgs e)
    {
        TextReader reader = new StreamReader(lyricspath);
        string[] read = File.ReadAllLines(lyricspath);
        string join = string.Join(" ", read);
        int number = join.Length;
        start++;
        string str = join.Substring(start, 15);
        if (start == number - 15)
        {
            start = 0;
        }
        label1.Text = str;
    }

is there any way to make the timer start completely over each time i uncheck then check the checkbox?

Upvotes: 1

Views: 13004

Answers (3)

Taryn
Taryn

Reputation: 247620

If you reset your start to zero on the check change event, that should reset the timer:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked == true)
        {
            start = 0;
            label1.Text = string.Empty;
            timer1.Enabled = true;
            timer1.Start();
        }
        else
        {
            timer1.Enabled = false;
        }
    }

I have a similar process in which I start a timer when a form loads, then if they have a form open for a period of time I give them the option to keep the form open. If they do, then I reset the timer count to zero and the process starts over.

Upvotes: 0

Metro Smurf
Metro Smurf

Reputation: 38335

Timer.Enabled and Timer.Start() are functionally equivalent.

I suspect, you'll need to reset your start variable.

if (checkBox1.Checked == true)
{
  start = 0;
  label1.Text = string.Empty;
  timer1.Start();
}
else
{
  timer1.Stop();
}

Edit to include the resetting of the label per comment.

Upvotes: 1

DRapp
DRapp

Reputation: 48139

set the INTERVAL property... in milliseconds... 1000 = 1 second

Upvotes: 1

Related Questions