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 2.0+

Detecting Screen Resolution Changes

Some applications need to detect when the user changes their screen resolution in order to ensure that the user interface remains correctly displayed. This detection is made possible with static events provided by the SystemEvents class.

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.

using Microsoft.Win32;

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