Ryan Peschel
Ryan Peschel

Reputation: 11746

What are my options for timing?

I'm making a TextBox control in XNA and do not have access to the GameTime class. Currently I am trying to simulate the blinking text cursor caret and have successfully done so using this code:

int deltaTickCount = Environment.TickCount - previousTickCount;

if (deltaTickCount < CursorBlinkRate && Selected)
{
    spriteBatch.Draw(emptyPixel, new Rectangle(caretLocation, Rectangle.Y + 1, caretWidth, caretHeight), Color.Black);
}
else if (deltaTickCount > CursorBlinkRate * 2)
{
    previousTickCount = Environment.TickCount;
}

However, I'm a bit wary of using Environment.TickCount. If the computer was running long enough, wouldn't the program eventually crash or produce unpredictable behavior when the tick count exceeded its integral size?

Does anyone know what Windows does? I imagine it would use the system clock. Would that be a more suitable solution? I imagine they used something like total milliseconds in to the second instead of the tick count, but I'm not sure.

Thanks for reading.

Upvotes: 0

Views: 217

Answers (3)

DIXONJWDD
DIXONJWDD

Reputation: 1286

I generally use the system diagnostics timer in a lot of situations.

It's a pretty powerful tool which creates a timer for you with a lot of good controls.

using System.Diagnostics;

Stopwatch timer = new Stopwatch();

Then use inbuilt controls:

timer.Start();
if(timer.elapsedMilliseconds() > ...)
{ }
timer.Reset();

etc...

This would allow you to reset the timer?

Upvotes: 2

Carey Gregory
Carey Gregory

Reputation: 6846

When Evnironment.TickCount rolls over, deltaTickCount will end up being negative, so you know it has happened. The calculation then becomes:

if (deltaTickCount < 0)
   deltaTickCount = int.MaxValue - previousTickCount + Environment.TickCount;

Upvotes: 1

Kyle W
Kyle W

Reputation: 3752

Without bothering with what would happen in the case of an integer overflow, simply change to:

int deltaTickCount = 
    Environment.TickCount > previousTickCount 
      ? Environment.TickCount - previousTickCount 
      : CursorBlinkRate * 3; 

Upvotes: 0

Related Questions