WPF - A more accurate Timer - c#

I'm new to CS and WPF. I'm going to get a DateTime object and set it as the beginning of my timer. But I used DispatcherTimer.Tick. I can feel it inaccurate with a little care and playing with window controls. It apparently its in a single thread beside other functions of program.
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
void timer_Tick(object sender, EventArgs e)
{
dateTime = dateTime.AddSeconds(1);
TimeTb.Text = dateTime.ToLongTimeString();
}
Is there another method to use for a more accurate timer?

Do not add up seconds. This is accurate:
private TimeSpan offset;
void timer_Tick(object sender, EventArgs e)
{
TimeTb.Text = (DateTime.Now - offset).ToLongTimeString();
}
If you want to show the time elapsed since a start time:
private DateTime start = DateTime.Now;
void timer_Tick(object sender, EventArgs e)
{
TimeTb.Text = (DateTime.Now - start).ToString();
}

Definitely. Take a look at the System.Diagnostics.Stopwatch class. You're re-inventing the wheel!

Related

Getting time until next event

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;

Timer C# use in game development

I have a game in C# and I need to allow tournament mode in which each round will be of 2 minutes. How can I display the time from 0:00 up till 2:00 on the form?
I have this in a constructor:
Timer timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
And this is the Event Handler
void Timer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = DateTime.Now.ToLongTimeString();
}
but I don't know how I can begin the time from 0:00 instread of the current time.. I tried creating a DateTime instance but when I do myDateTime.ToString(); in the event handler, it just remains 0:00.
I tried searching but I can't find anything related.
Thanks a lot !
Save current time to field when you are starting timer:
_startTime = DateTime.Now;
timer.Start();
And calculate difference later:
void Timer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = (DateTime.Now - _startTime).ToString(#"mm\:ss");
}
You need a member variable that is in scope for both the timer initialization and the Timer_Tick event handler.
class Something
{
DateTime _myDateTime;
Timer _timer;
public Something()
{
_timer = new Timer();
_timer.Interval = 1000;
_timer.Tick += Timer_Tick;
_myDateTime = DateTime.Now;
_timer.Start();
}
void Timer_Tick(object sender, EventArgs e)
{
var diff = DateTime.Now.Subtract(_myDateTime);
this.textBox1.Text = diff.ToString();
}
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
void Timer_Tick(object sender, EventArgs e)
{
label1.Text = stopWatch.ElapsedTicks.ToString();
}
You can store a DateTime.Now when you start the timer and then in every timer tick handler calculate how much time has passed between DateTime.Now and the stored start date. If you have a pause, you will need to also keep track of how long the game has been paused.
Considering the inconviniences with the above method, I would suggest you declare a StopWatch somewhere, instantiate and start it where you call timer.Start and then in your timer tick just read the Elapsed property of the StopWatch. You can even Stop and Start (pause) it if you need.

DispatcherTimer apply interval and execute immediately

Basically when we apply some interval ie 5 sec we have to wait for it.
Is it possible to apply interval and execute timer immediately and don't wait 5 sec?
(I mean the interval time).
Any clue?
Thanks!!
public partial class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
timer.Tick += new EventHandler(timer_Tick);
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("!!!");
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
}
}
There are definitely more elegant solutions, but a hacky way is to just call the timer_Tick method after you set the interval initially. That'd be better than setting the interval on every tick.
Initially set the interval to zero and then raise it on a subsequent call.
void timer_Tick(object sender, EventArgs e)
{
((Timer)sender).Interval = new TimeSpan(0, 0, 5);
MessageBox.Show("!!!");
}
could try this:
timer.Tick += Timer_Tick;
timer.Interval = 0;
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
if (timer.Interval == 0) {
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Start();
return;
}
//your timer action code here
}
Another way could be to use two event handlers (to avoid checking an "if" at every tick):
timer.Tick += Timer_TickInit;
timer.Interval = 0;
timer.Start();
//...
public void Timer_TickInit(object sender, EventArgs e)
{
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Tick += Timer_Tick();
timer.Start();
}
public void Timer_Tick(object sender, EventArgs e)
{
//your timer action code here
}
However the cleaner way is what was already suggested:
timer.Tick += Timer_Tick;
timer.Interval = SOME_INTERVAL;
SomeAction();
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
SomeAction();
}
public void SomeAction(){
//...
}
That's how I solved it:
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
dispatcherTimer.Start();
DispatcherTimer_Tick(dispatcherTimer, new EventArgs());
Works for me without any issues.
Disclaimer: This answer is not for the OP because he wants to use DispatcherTimer
But if you do not have this limitation and you can use another Timer, then there is a cleaner solution
You can use System.Threading.Timer
The most important thing is setting dueTime:0
System.Threading.Timer timer = new Timer(Callback, null, dueTime:0, period:10000);
The documentation of the dueTime is the following
The amount of time to delay before callback is invoked, in milliseconds. Specify Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.
and your callback is like this
private void Callback(object? state) =>
{
}
Again this does not use DispatcherTimer but it could solve your problem
Related answer

how can i get timer in wpf mediaplayer

i have developed media player in WPF.but i did n't get timer for slider in that.how i will get that timer below is the my .cs file code.
i used dispatchertimer for timer.video is seeking but timer is not displaying with video.
seekbar not moving where i clicked in seekbar.plz help me .
thanks in advance.
DispatcherTimer timer;
public TimeSpan duration;
public Window1()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(400);
timer.Tick += new EventHandler(timer_tick);
Loaded += new RoutedEventHandler(Window_Loaded);
}
private void mediaElement1_MediaOpened(object sender, RoutedEventArgs e)
{
if (mediaElement1.NaturalDuration.HasTimeSpan)
{
TimeSpan ts = mediaElement1.NaturalDuration.TimeSpan;
slider1.Maximum = ts.TotalSeconds;
slider1.SmallChange = 1;
slider1.LargeChange = Math.Min(10, ts.Seconds / 10);
}
timer.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
slider1.Value = mediaElement1.Position.TotalSeconds;
}
take a look at this
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
You can implement this but you will have to pass references to your controls/window because without having references to your controls, the thread/timer object cannot modify controls (ie text etc).
Hope that helps!
Edit: Sorry I misread, but definately check whether the timer youre using can make changes to your elements

how do I delay action on mouse enter rectangle c#

I would like to delay an action by several seconds after a mouse pointer has entered and remained for period of time in a winform graphics rectangle. What would be a way to do this?
Thanks
c#, .net 2.0, winform
private Timer timer;
private void rect_MouseEnter(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = 3000;
timer.Start();
timer.Tick += new EventHandler(t_Tick);
}
private void rect_MouseLeave(object sender, EventArgs e)
{
timer.Dispose();
}
void t_Tick(object sender, EventArgs e)
{
timer.Dispose();
MessageBox.Show(#"It has been over for 3 seconds");
}
Something such as:
static void MouseEnteredYourRectangleEvent(object sender, MouseEventArgs e)
{
Timer delayTimer = new Timer();
delayTimer.Interval = 2000; // 2000msec = 2 seconds
delayTimer.Tick += new ElapsedEventHandler(delayTimer_Elapsed);
}
static void delayTimer_Elapsed(object sender, EventArgs e)
{
if(MouseInRectangle())
DoSomething();
((Timer)sender).Dispose();
}
Probably could be done more efficiently, but should work :D
Two ways to set up MouseInRectangle -> one is to make it get the current mouse coordinates and the position of the control and see if it's in it, another way would be a variable which you would set to false on control.mouse_leave.
Try using the Timer control (System.Windows.Forms.Timer).
Please notice System.Windows.Forms.Timer is not Exact and you cannot rely it will act on exactly the interval given.
it would be prefeable to use System.Times.timer and use the Invoke action to return to the GUI thread.

Categories

Resources