Out of interest, I was trying to make a counter in Winforms that when a button is clicked it will update the text one by one until target number is reached. I.e if I wanted to count from 1-100. When the button is clicked I don’t want it to go instantly to 100. I want it to go 1,2,3,4,… etc until it has reached 100.
This is what I have so far, and it still just jumps instantly to the target. Any ideas on how to achieve this effect ??
Use a timer control, so you aren’t holding the GUI thread hostage.
This is the correct answer. Timer events run on the UI thread, so updating another control’s value from the timer event works correctly and all repainting should happen naturally.
If you do not choose to use a timer, you better know what you’re doing with respect to the UI thread and using Invoke to correctly update the values of the controls on your form. Do not use Thread.Sleep() because it’s not appropriate for what is desired.
The easiest, cleanest solution in a Windows Forms app is to create a Timer control, set the desired interval, and stop/start the timer as needed for your application.
Handle your button click event
is the timer already running? if so, return. (or maybe you want to be able to toggle the feature on/off? that’s for you to decide)
reset current value to 0
enable the timer
Handle the Timer Tick event
increment the current value
display the current value
if the current value is high enough, disable the timer.
and that’s all there is. No looping. No Thread.Sleep.
Notice that BOTH event handlers require access to “current value” whatever variable that is (and please don’t use “x”). This means while not exactly “global” in the javascript sense it needs to be “global to the class” as u/modi123_1 suggests. I recommend making it a property of the Form. Thus, each event handler can read/write the property as needed.
Timer Tick: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.timer.tick?view=net-5.0
Do you want it to count up by one each time you click on the button, or do you want a single click to start it slowly counting up without you needing to click any more?
Slowly count up without needing to click
It does exactly what you want but really fast
Maybe you could use:
Thread.Sleep();
X needs to be global.
Maybe something like
Hello, MoneyPotion: code blocks using backticks (“`) don’t work on all versions of Reddit!
Some users see this / this instead.
To fix this, indent every line with 4 spaces instead. It’s a bit annoying, but then your code blocks are properly formatted for everyone.
An easy way to do this is to use the code-block button in the editor. If it’s not working, try switching to the fancy-pants editor and back again.
Comment with formatting fixed for old.reddit.com users
FAQ
You can opt out by replying with backtickopt6 to this comment.
C# devs
null reference exceptions