C
C
cheIowek2021-09-22 19:46:47
C++ / C#
cheIowek, 2021-09-22 19:46:47

Why does the timer counter on windows forms increase by 2 and not by 1?

Hello everyone, you need to make sure that the variable in the class increases by one each time the timer fires. I did the following and I can't figure out why the counter is incrementing by 2?
The form only has a timer and a label.

public partial class Form1 : Form
    {
        class myClass
        {
            static public int counter = 0;
        }
        public Form1()
        {
            InitializeComponent();
            
            timer1.Interval = 200;
            timer1.Start();
            timer1.Tick += timer1_Tick;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            myClass.counter++;
            label1.Text = myClass.counter.ToString();
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Foggy Finder, 2021-09-22
@cheIowek

The fact is that there are 2 different subscriptions to the Tick event - one "automatic" created by the form designer and the second "own".
VS shows all links if you click on "reference" at the top:
614b6a2b8e3c2686381595.png
Removing one of them will give the expected behavior.

C
cicatrix, 2021-09-23
@cicatrix

You most likely have two Tick subscriptions.
Here is this line in your constructor:
timer1.Tick += timer1_Tick;
And the exact same one, most likely, is present in Form1.Designer.cs. Take away one of them

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question