BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

System Information
.NET 1.1+

Detecting a System Time Change

When developing software that uses the system time, it can be necessary to react when a user makes a change to the time using the Control Panel. It is possible to detect such alterations using an standard event, which is defined in the SystemEvents class.

SystemEvents

The SystemEvents class is a standard type in the .NET framework, found within the Microsoft.Win32 namespace. It defines a number of events that are raised when the user performs operating system functions. These can be subscribed to in the same manner as any other event.

If you need to detect a change to the clock, you can subscribe to the TimeChanged event. If the user modifies the date or time, the event will be raised and you can react accordingly. There is an issue with the event; it may be raised twice for a single change in the time. If this would cause a problem in your scenario, or if the action you perform when the time changes uses lots of resources, you should attempt to detect and ignore repeated events.

To show the use of the event, create a new console application and add the following using directive to the automatically generated class:

using Microsoft.Win32;

You can now add the code shown below. Here the Main method subscribes to the event before pausing for user input. Whilst waiting in this state, any change to the system time will trigger the event and display a message.

static void Main()
{
    SystemEvents.TimeChanged += SystemEvents_TimeChanged;
    Console.ReadLine();
}

static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
    Console.WriteLine("Time changed");
}
9 January 2013