Saturday, February 8, 2014

Detecting System Time Change Event

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;

static void Main(string[] args)
{
    SystemEvents.TimeChanged += SystemEvents_TimeChanged;
    Console.ReadLine();
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
    Console.WriteLine("Time changed");
}

No comments:

Post a Comment