The OS sends the WM_TIMECHANGE message to the window procedure
Then you can compare the System time (DateTime.Now) with the time you can measure with Stopwatch for example
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello,
In my C# WPF desktop project, I want to detect if the system clock has been moved forward or backward. When such a change is detected, I would like to take specific actions.
For example:
Show a warning if the system clock is moved forward.
Log an entry if the system clock is moved backward.
How can I implement this check? What would be the best method or practice to detect changes in the system clock?
Thank you in advance!
The OS sends the WM_TIMECHANGE message to the window procedure
Then you can compare the System time (DateTime.Now) with the time you can measure with Stopwatch for example
Hi, @fatih uyanık. Welcome to Microsoft Q&A.
Design ideas:
System clock deviation generally occurs at the millisecond level. At the beginning, record DateTime _lastCheckedTime=DateTime.Now
, then the expected time after 5 seconds is _lastCheckedTime+5 seconds
, but after 5 seconds, get DateTime now = DateTime.Now;
again, there will be a time deviation, which is in milliseconds, and _lastCheckedTime+5 seconds-now
could get the system clock deviation.
DispatcherTimer
could execute the bound function of DispatcherTimer.Tick
at every DispatcherTimer.Interval
time. This allows the system clock to be checked once every DispatcherTimer.Interval
time.
Related code
public class DetectSystemClock
{
private DateTime _lastCheckedTime;
private readonly TimeSpan _checkInterval = TimeSpan.FromSeconds(5); // Check interval:Perform a check every 5 seconds
private DispatcherTimer timer = new DispatcherTimer();
public DetectSystemClock()
{
timer.Interval = _checkInterval;
timer.Tick += Timer_Tick;
}
/*Create a `DetectSystemClock` object and run `StartDetect()` to perform a system clock check*/
public void StartDetect()
{
_lastCheckedTime = DateTime.Now;
timer.Start();
}
private void Timer_Tick(object? sender, EventArgs e)
{
DateTime now = DateTime.Now;
DateTime expectedTime = _lastCheckedTime.Add(_checkInterval);
TimeSpan timeDifference = now - expectedTime;
if (timeDifference.TotalSeconds > 0)
{
//TODO: Generate a warning
Debug.WriteLine($"System clock moved backward {timeDifference}.");
}
else
{
//TODO: Record an entry
Debug.WriteLine($"System clock moved backward {timeDifference}.");
}
_lastCheckedTime = now;
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.