Why the timet count backwards not showing the counting on the label? - c#

In the top of form1 i have:
private int seconds;
private int minutes;
private int hours;
In the constructor:
seconds = 0;
minutes = 20;
hours = 0;
label9.Visible = false;
label9.Text = "00:00:00";
Then the timer 3 tick event. I used a breakpoint on the timer3 tick event i see that the minutes and seconds are coundting backwards but label 9 is not updating.
Maybe the string.Format on label9 is not right ?
private void timer3_Tick(object sender, EventArgs e)
{
// Verify if the time didn't pass.
if ((minutes == 0) && (hours == 0) && (seconds == 0))
{
// If the time is over, clear all settings and fields.
// Also, show the message, notifying that the time is over.
timer3.Enabled = false;
label9.Visible = true;
label9.Text = "00:00:00";
}
else
{
// Else continue counting.
if (seconds < 1)
{
seconds = 59;
if (minutes == 0)
{
minutes = 59;
if (hours != 0)
hours -= 1;
}
else
{
minutes -= 1;
}
}
else
seconds -= 1;
// Display the current values of hours, minutes and seconds in
// the corresponding fields.
label7.Visible = true;
label9.Visible = true;
label9.Text = string.Format("{00} : {00} : {00}", hours.ToString(), minutes.ToString(),seconds.ToString());
}
}
All i see in the end on label 9 is: 0:0:0 thats it and i dont see 20 minutes counting backward.

You need to fix your string formatting, that's the culprit:
label9.Text = string.Format("{0:00} : {1:00} : {2:00}", hours, minutes, seconds);
Also - consider using some other mechanism (e.g. Stopwatch class) for calculating elapsed time; you can't guarantee that the code as written will execute exactly every 1000 ms.

Related

C# WFA - increase value until limit then decrease loop

I want to do a program in C# - WFA, in which while a button is pressed - the label 1 value is increased by 10 since it reaches 100, then in decreases to 0 and again is increased til 100
like: 0 10 20 30...80 90 100 90 80...20 10 0 10...
i tried this:
private static int i = 0;
protected void button1_MouseClick(object sender, MouseEventArgs e)
{
if (i < 100)
i = i + 10;
else
i = i - 10;
this.label1.Text = i.ToString();
}
but it just decrease from 100 to 90 and the increases back to 100 and goes like this
You need to save two state information about the current value outside the button1_MouseClick() method. One is the value i, which you already do. The other is the information if you are going up or down. You can save this in a simple bool value like:
public static bool goingUp=true;
Then you can use these two fields i and goingUp and decide what you want to do:
if (goingUp)
{
i += 10;
if (i >= 100)
{
goingUp = false;
}
}
else
{
i -= 10;
if (i <= 0)
{
goingUp = true;
}
}
this.label1.Text=i.ToString();
an easy way would be this one
_indexValue = (_indexValue + 1) % 100;
and when it hits 100 then it restart to 0

Windows fourm crashes after clicking button

I decided to create a basic timer just for my use and everytime i click the start button the program freezes up completely. Im i missing something obvious or?
namespace Timer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Start_Click(object sender, EventArgs e)
{
int secs = 0, mins = 0, hours = 0;
for (int num1 = 1; num1 > 0;)
{
txt_secs.Text = secs.ToString() ;
System.Threading.Thread.Sleep(1000);
secs = secs + 1;
if (secs == 60)
{
secs = 0;
mins = mins + 1;
txt_mins.Text = mins.ToString();
}
if (mins == 60)
{
mins = 0;
hours = hours + 1;
txt_hours.Text = hours.ToString();
}
}
}
}
}
The issue is in System.Threading.Sleep()
Per Microsoft Documentation your thread will be suspended. The thread is in an infinite loop and thus will be (essentially) permanently suspended.
Consider using Timers or the Stopwatch Class or (if you need threading) System.Threading.Timer Instead

Countdown timer in Unity C script

I have been working on a Unity project for sometime, I have a timer which currently counts down from around 30 minutes, however I want this to be 4 hours counting down. here is my code:
seconds = Mathf.CeilToInt (gameTimer - Time.timeSinceLevelLoad) % 60;
minutes = Mathf.CeilToInt (gameTimer - Time.timeSinceLevelLoad) / 60;
}
if (seconds == 0 && minutes == 0) {
chestfree.gameObject.SetActive(true);
checker = 2;
}
remainingTime = string.Format("{0:00} : {1:00}", minutes, seconds);
if (seconds != 0 && minutes != 0) {
h.text = remainingTime.ToString ();
} else {
h.text = "Get";
}
So you can see I have seconds and minutes in there, I tried to change the / 60 after minutes to 19 and when it ran it displayed 240 minutes which was fine, but the countdown seems to be very odd, minutes go down after around 20 seconds so I know thats not the right way to do it!
Can anyone explain to me how to add in hours or how I can make the minutes count down from 240 minutes?
Many thanks!
Untested code below:
hours = Mathf.FloorToInt((float)(gameTimer - Time.timeSinceLevelLoad) / 3600);
minutes = Mathf.FloorToInt((float)(gameTimer - Time.timeSinceLevelLoad-hours*3600) / 60);
seconds = Mathf.FloorToInt((gameTimer - Time.timeSinceLevelLoad) % 60);
if (seconds == 0 && minutes == 0 && hours == 0) {
chestfree.gameObject.SetActive(true);
checker = 2;
}
//remainingTime = string.Format("{0}:{1}:{2}",hours,minutes,seconds);
remainingTime = string.Format("{2:00} : {0:00} : {1:00}", minutes, seconds,hours);
if (seconds != 0 && minutes != 0 && hours != 0) {
h.text = remainingTime.ToString ();
} else {
h.text = "Get";
}
I'm not sure about the construction of the remainingTime string. I would have used something like this:
remainingTime = string.Format("{0}:{1}:{2}",hours,minutes,seconds);
EDIT:
(gameTimer - Time.timeSinceLevelLoad)/60 is an integer operation, that's why it did not work. By forcing float operation it should work.

How do i show/display a counter count back from 20 minutes to 0?

My program finished the operation from now to next update time. i want to show the user a counter clock count in the format: 00:00:00
Then 00:20:00 and count 20 minutes back.
This is the code where the operation is finished and timer1 should start:
private void DownloadCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
//... download cancelled...
}
else if (e.Error != null)
{
//... download failed...
Logger.Write("Error: " + e.Error);
}
ActiveDownloadJob adJob = e.UserState as ActiveDownloadJob;
ProgressBar pb = (adJob != null) ? adJob.ProgressBar : null;
lock (_downloadQueue)
{
if (_downloadQueue.Count == 0)
{
if (pb != null)
{
pb.Tag = null;
timer2.Stop();
label8.ForeColor = Color.Green;
label8.Text = "Process Finished";
label7.Visible = true;
Timer3 tick event if empty now but i think there i should make and display the counter back.
Set the execution time, 20 minutes into the future
var rut_at = DateTime.Now().AddMinutes(20);
And bind or refresh every second a variable called timeLeft that is defined as
var timeLeft = run_at - DateTime.Now();

Countdown Timer Skipping Time in C#

I Have This in C#
private void counter_Tick(object sender, EventArgs e)
{
Time.Text = String.Format("{0:000}", Hour) + ":" + String.Format("{0:00}", Minute) + ":" + String.Format("{0:00}", Second);
if (Second != 00)
{
Second = Second - 1;
}
else if (Minute != 00)
{
Minute = Minute - 1;
Second = 59;
}
else if (Hour != 00)
{
Hour = Hour - 1;
Minute = 59;
}
else
{
counter.Stop();
Time.ForeColor = Color.Red;
}
}
Which Does work but when it gets to minus an hour to add to minutes, it goes from 00 minutes to 58 minutes instead of 59
EG.
From: 001:00:00
To: 000:58:59
And is there a better way to make a countdown timer that does something when it hits 000:00:00???
Well let's see what happens when the time is 10:00:00.
Subtract one hour: 09:00:00.
Set minutes to 59: 09:59:00.
If you notice the time is off by one minute (10:00:00 - 09:59:00 = 00:01:00). The solution is to set the seconds to 59 also. So now our code is.
// ...
else if (Hour != 00)
{
Hour = Hour - 1;
Minute = 59;
Second = 59;
}
// ...
You can use standard .Net classes for subtracting time:
private TimeSpan timeSpan;
private TimeSpan oneSecond = new TimeSpan(0, 0, 1);
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Time.Text = timeSpan.ToString();
if (timeSpan == TimeSpan.Zero)
{
Time.ForeColor = Color.Red;
timer.Stop();
return;
}
timeSpan -= oneSecond;
}
Initialize timespan when you starting your timer (I used System.Timers.Timer):
timeSpan = new TimeSpan(1, 0, 0);
Timer timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
You also need to set Second to 59. Else, once the timer ticks again, it immediately switches to else if (Minute != 00) and decrements Minute (which is already 59) by one.
DateTime start;
DateTime final;
private void start()
{
start = DateTime.Now;
final = start + TimeSpan.FromHours(1);
}
private void counter_Tick(object sender, EventArgs e)
{
start = DateTime.Now;
Time.Text = (final-start).Hours.ToString() + ":" + (final-start).Minutes.ToString() + ":" + (final-start).Seconds.ToString();
if (final == start)
{
//final code
}
}

Categories

Resources