In this code after starting timer again it starts from the current value instead of the vale it stopped. How to pause this timer?
public Page1()
{
InitializeComponent();
_rnd = new Random();
_timer = new DispatcherTimer();
_timer.Tick += new EventHandler(TimerTick);
_timer.Interval = new TimeSpan(0, 0, 0, 1);
}
void TimerTick(object sender, EventArgs e)
{
var time = DateTime.Now - _startTime;
txtTime.Text = string.Format(Const.TimeFormat, time.Hours, time.Minutes, time.Seconds);
}
public void NewGame()
{
_moves = 0;
txtMoves.Text = "0";
txtTime.Text = Const.DefaultTimeValue;
Scrambles();
while (!CheckIfSolvable())
{
Scrambles();
}
_startTime = DateTime.Now;
_timer.Start();
//GridScrambling.Visibility = System.Windows.Visibility.Collapsed;
}
private void Pause_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
NavigationService.Navigate(new Uri("/Page4.xaml", UriKind.Relative));
_timer.Stop();
}
private void Play_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
_timer.Start();
}
As this says that the Stop method only changes the IsEnabled property and this says that this property only prevents the Tick event to be raised, I don't think that there is a method to simply 'pause' the timer. The best way is to reinitialize the timer each time you have "paused" it, if you really want it to start clean again.
But I do not think that this is you real problem. When you pause your game the timer stops working. When you continue it the timer starts working again. When you now try the calculate the time from THIS moment till the start time, then you make a big mistake: you have to ignore the paused time. Because when you play the game 2s, then pause it for 10s and then continue the game, the timer shows 12s, instead of 2s, doesn't it? Maybe you should store the paused times in a variable and substract that from the real game time.
Related
I am new to coding and are having trouble.
I want to use a timer that will start upon pressing ScatterMode tab, it will start counting 4sec before running "Dosomething" function. This cycle will repeat itself until i decide to stop the program. But the problem i get is, this code only run correctly for like 2loop, after that the timer sort of go crazy LOL.
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething);
timer.Start();
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop();
timer.Enabled = false;
Grab.buffer(out buffer, out status, 6000);
Scatter_mode(buffer);
pictureBox1.Refresh();
int done_grab = 1;
if (doneGrab == 1)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
timer.Start();
done_grab = 0;
}
}
Adding a new event handler to a timer, to handle its tick event, inside the handler for the tick event will indeed cause the timer to go "crazy". Every time the timer raises its event, another event handler (that responds to events raised) will be added. This means the next time the timer ticks, the event code will run twice. Two new event handlers will be added. Next time the timer ticks, the code will run 4 times. 4 event handlers will be added ... and so on
Remove this line from your code:
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
And move this line into your form's constructor:
timer.Tick += new EventHandler(Dosomething);
You only want to wire this event handler up once. Every time the timer's interval elapses, the code will run, once :)
I'll also do a bit of a peer review of your code, see the comments:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000; //can go in the constructor also; don't need to set repeatedly
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething); //move to constructor
timer.Start(); //this isn't needed - you already Enabled the timer, which started it
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop(); //use this
timer.Enabled = false; //or this. It's not required to do both
Grab.buffer(out buffer, out status, 6000); //if these lines crash then your timer will
Scatter_mode(buffer); //only restart if the toolstripmenuitemclick
pictureBox1.Refresh(); //above runs.. is it what you wanted?
int done_grab = 1; //not needed
if (doneGrab == 1) //this will always evaluate to true, it is not needed
{
timer.Interval = 4000; //the interval is already 4000, not needed
timer.Enabled = true; //careful; your timer may stop forever if the code above crashes
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click); //remove
timer.Start(); //not needed
done_grab = 0; //not needed
}
}
I've created a C# windows form application that uses a timer to clear the input boxes every 5 minutes. There is a label called lblTime that displays the amount of time elapsed at any given point while the application is open.
I would like to be able to disable or pause the Timer (Clock.Enabled = false) with a button click, and have lblTime stay on the amount of time elapsed when the button was clicked. However, due to the way that the elapsedTime variable is calculated (DateTime.Now - startTime), this value carries on changing even after the timer has been disabled.
So, to sum up:
lblTime displays running time as Clock ticks
Clock can be disabled by button click, but lblTime carries on incrementing
lblTime needs to stop on current value on same button click that disables Clock, and then be able to start counting again from that same value.
Code that starts Clock, initialises and updates lblTime is displayed.
Any help would this would be very much appreciated,
Thanks,
Mark
private void btnStart_Click(object sender, EventArgs e)
{
//Timers set to start ticking
Clock.Enabled = true;
startTime = DateTime.Now; //the milisecond that btnStart is clicked
initialiseClock();
initialiseIntervalCounter();
}
private void initialiseClock() //initialisation of Clock Timer
{
Clock = new System.Windows.Forms.Timer();
Clock.Tick += new EventHandler(Clock_Tick); //calls Clock EventHandler
Clock.Interval = 1000; //1 second in miliseconds
Clock.Start();
}
private void Clock_Tick(object sender, EventArgs e) //Clock EventHandler definition
{
updateTimeDisplay();
checkDisplay();
}
private void updateTimeDisplay()
{
elapsedTime = (DateTime.Now - startTime);
lblTime.Text = Convert.ToString(elapsedTime);
}
Use a bool flag and a TimeSpan and a counter for the seconds until the next clearing:
DateTime startTime = DateTime.Now;
TimeSpan elapsed = new TimeSpan(0);
bool running = true;
int clearInSeconds = 300;
private void Clock_Tick(object sender, EventArgs e)
{
// function one: count elapsed running time
if (running) elapsed = elapsed.Add(new TimeSpan(0, 0, 1));
lblTime.Text = startTime.Add(elapsed).ToLongTimeString();
// function two: clear stuff after interval:
if (clearInSeconds-- <= 0)
{
clearInSeconds = 300;
// clear your stuff now
}
}
Use your button click to switch between running and not running. I used a click on the label:
private void lblTime_Click(object sender, EventArgs e)
{
running = !running;
}
Change the method in which the countdown time is used. Use a TimeSpan datatype. Initialize the variable to 5 minutes New TimeSpan(0, 5, 0) and use it instead of a start time and Now().
I am working on stopwatch. If I select the start button the timer is running fine. But when I press the button again with the following code. Then the timer starts from beginning 00:00:00. I want to pause the timer and if I press it, again it should start from the paused time, not from the beginning time. How to do this task? Any other ideas are also accepted.
private void Timer_Tick(object sender, EventArgs e)
{
TimeSpan runTime = TimeSpan.FromMilliseconds(System.Environment.TickCount - _startTime);
timeLabel.Text = runTime.ToString(#"hh\:mm\:ss");
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
if (_timer.IsEnabled)
{
_watcher.Stop();
_timer.Stop();
StartButton.Content = "Start";
}
else
{
_watcher.Start();
_timer.Start();
_startTime = System.Environment.TickCount;
StartButton.Content = "Stop";
}
}
Just get the timer time when you click on stop button and change your code when you click on start button.
Start button :
Check if _refreshTimeTimer is not null
well
if(_refreshTimeTimer != null){
Timer t = new timer(_refreshTimeTimer );
// Start new timer
_refreshTimeTimer = null;
}else{
if (_timer.IsEnabled)
{
_watcher.Stop();
_timer.Stop();
StartButton.Content = "Start";
}
else
{
_watcher.Start();
_timer.Start();
_startTime = System.Environment.TickCount;
StartButton.Content = "Stop";
}
}
Stop button :
_refreshTimeTimer = _timer.getTime();
You have to declare dispatcher time , run timer at what time do you want to pause then start your first time add dispatcher timer value it will start from before paused time.
I have a sync timer in my app that fires up a function at a given time... now I want to know how much time is left until the next call to that function.
This is my call to the timer:
var syncTime = time.activitylog;
double time = TimeSpan.Parse(syncTime).TotalMilliseconds;
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = time;
myTimer.Start();
How do I get the time until next call?
Thanks
You can use another timer, and set the Interval of that the value that you want,exactly a part time of the Interval of original timer.
Then start them Simultaneously,I mean at the same time.
UPDATE :
Maybe this code describes my solution better :
public Form1()
{
InitializeComponent();
}
System.Windows.Forms.Timer trOriginal = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer trRemain = new System.Windows.Forms.Timer();
double remain = 0;
private void button1_Click(object sender, EventArgs e)
{
trOriginal.Interval = 1000;
trRemain.Interval = 1;
trOriginal.Tick += new EventHandler(trOriginal_Tick);
trRemain.Tick += new EventHandler(trRemain_Tick);
trOriginal.Start();
trRemain.Start();
}
void trRemain_Tick(object sender, EventArgs e)
{
remain -= trRemain.Interval;
Console.WriteLine("remain MS to next event : " + remain);
}
void trOriginal_Tick(object sender, EventArgs e)
{
remain = trOriginal.Interval;
}
You can use a System.Diagnostics.Stopwatch to keep track of how much time has passed already and restart the Stopwatch with every tick of your Timer.
Stopwatch watch = new Stopwatch();
private void DisplayTimeEvent(object sender, EventArgs e)
{
watch.Restart();
// Whatever is supposed to happen, when the timer ticks
}
Now whenever you want to know how much time is left until the event is fired next, you can do this:
long timeLeft = myTimer.Interval - watch.ElapsedMilliseconds;
I have four buttons that are called "ship1,ship2" etc.
I want them to move to the right side of the form (at the same speed and starting at the same time), and every time I click in one "ship", all the ships should stop.
I know that I need to use a timer (I have the code written that uses threading, but it gives me troubles when stopping the ships.) I don't know how to use timers.
I tried to read the timer info in MDSN but I didn't understand it.
So u can help me?
HERES the code using threading.
I don't want to use it. I need to use a TIMER! (I posted it here because it doesnt give me to post without any code
private bool flag = false;
Thread thr;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
flag = false;
thr = new Thread(Go);
thr.Start();
}
private delegate void moveBd(Button btn);
void moveButton(Button btn)
{
int x = btn.Location.X;
int y = btn.Location.Y;
btn.Location = new Point(x + 1, y);
}
private void Go()
{
while (((ship1.Location.X + ship1.Size.Width) < this.Size.Width)&&(flag==false))
{
Invoke(new moveBd(moveButton), ship1);
Thread.Sleep(10);
}
MessageBox.Show("U LOOSE");
}
private void button1_Click(object sender, EventArgs e)
{
flag = true;
}
Have you googled Windows.Forms.Timer?
You can start a timer via:
Timer timer = new Timer();
timer.Interval = 1000; //one second
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.Start();
You'll need an event handler to handle the Elapsed event which is where you'll put the code to handle moving the 'Button':
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MoveButton();
}