Friday, December 7, 2007

Stopping Time

As mentioned in a previous post, Mobile Stopwatch uses System.Environment.TickCount as a timer reference. If you record the TickCount value when the stopwatch starts, the elapsed time can be calculated by subtracting the initial TickCount value from the current TickCount value. The only problem with this method occurs when a Windows Mobile device goes into suspend mode and TickCount is not updated. Suspend mode effectively stops the stopwatch and it is restarted when suspend mode ends.

One solution to this problem is to prevent the device from entering suspend mode while the stopwatch is running. It turns out this is a rather simple thing to do since the Windows Mobile SDK provides us with an API for resetting the device's idle timer:
void WINAPI SystemIdleTimerReset(void);
Periodically calling this function will prevent a Windows Mobile device from suspending - we only need to determine how often this function needs to be called. Fortunately, the registry holds this information at the following key location:
Key: HKLM\SYSTEM\CurrentControlSet\Control\Power\Timeouts
Value: BattSuspendTimeout
Type: DWORD
The value stored here indicates the number of seconds that must elapse before the device enters suspend mode. As long as you call SystemIdleTimerReset() more frequently than this timeout value, the device will not suspend and TickCount will keep updating.

The down side of this solution is that your battery life will suffer if the stopwatch needs to run for long periods of time. I'll present a solution that resolves that dilemma in a future posting.

Note, it is still possible to turn off the display by pressing the device's power button, but this shouldn't be confused with the device entering a suspended state.

[As a side note, suspend mode is only an issue on Windows Mobile Professional. Windows Mobile Standard doesn't enter suspend mode, but only turns off the display.]

No comments: