Home > DeveloperSection > Forums > Can't stop a timer in c#
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    December-18-2013 12:50 AM

 C# C# 
Ratings:


 1 Reply(s)
 992  View(s)
Rate this:

I want the timer to stop when the ImageNumber is equal to zero.                                                                                                                                

 private void Health_Regen_Tick(object sender, EventArgs e)

    {

        if (ImageNumber1 == 0)

        {

            Health_Regen.Enabled = false;

        }

        if (ImageNumber1 < 20)

        {

            ImageNumber1 += 1;

            HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");

        }

    }

If I add a return statement after the first if statement the second if statement is disabled.



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    December-18-2013 1:25 AM

Hi Jeet,

Replace

if (ImageNumber1 == 0)

with

if (ImageNumber1 >= 20)

Your timer will already stop when ImageNumber1 equals 0, but it just never counts down to 0.

Also if you change ImageNumber1 to 0. It may already be running the timer which will increment it by one and skip the stopper, so pretty much the way you have it coded it's based on luck right now.

The luck happens if you change ImageNumber1 while timer is already running.

Try this:

        if (ImageNumber1 == 0) {

            Health_Regen.Enabled = false;

        } else if (ImageNumber1 < 20) {

            ImageNumber1 += 1;

            HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");

        }

Still the luck may still happen best you can do is stop the timer outside the timer when you make it ImageNumber1 = 0;


Don't want to miss updates? Please click the below button!

Follow MindStick