System Events
Although uncommon, there are situations where you will need to detect a change in the screen resolution. You might be creating an application that behaves differently on lower resolution displays than those with a greater available area, or you might have some other reason to react to a resolution change. In any case, you can identify the change using two system events.
The events are named DisplaySettingsChanged and DisplaySettingsChanging. Both are defined as static events in the SystemEvents class. DisplaySettingsChanged is raised after the screen resolution has been changed in the Control Panel utility or via some other software. DisplaySettingsChanging runs slightly earlier, as the display details are being modified.
To demonstrate the events we can use a simple console application project. Create the project and add the following using directive to the initial class, as SystemEvents is found in the Microsoft.Win32 namespace.
We can now subscribe to the events using the standard syntax. In the code below, both events are attached, each calling a method that displays a message. After subscribing, the Console.ReadKey call waits for any key to be pressed before unsubscribing from the events and exiting. You should always unsubscribe from DisplaySettingsChanged and DisplaySettingsChanging; both are static events and forgetting to unsubscribe will cause a memory leak.
static void Main()
{
SystemEvents.DisplaySettingsChanging += SystemEvents_DisplaySettingsChanging;
SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
Console.WriteLine("Change your display settings or press any key to quit");
Console.ReadKey();
SystemEvents.DisplaySettingsChanging -= SystemEvents_DisplaySettingsChanging;
SystemEvents.DisplaySettingsChanged -= SystemEvents_DisplaySettingsChanged;
}
static void SystemEvents_DisplaySettingsChanging(object sender, EventArgs e)
{
Console.WriteLine("Display settings changing");
}
static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
Console.WriteLine("Display settings changed");
}
Try running the program and changing screen resolution using the Control Panel to see the resultant messages.
15 August 2013