Changing Display Settings Programmatically


Previously, we have talked about how to change screen resolution and color system via DirectX. Today, we are talking about how to change all display settings -not the resolution and color system only- via API. We will change screen resolution (bounds,) color system (bit count,) rotation (orientation,) and refresh rate (frequency) via API with C# and the .NET Framework.


This lesson firstly discusses the required functions and structures. Then, it focuses on how to retrieve current display settings. After that, it discusses how to get all modes supported by your display. As you already know, a mode is a combination of may display settings including bounds, bit count, orientation, and frequency; therefore, we will refer to display settings as display mode.
Finally, this lesson discusses how to change the current display settings. Along with the discussion, you will learn additional techniques like how to PInvoke Win32 API functions, and to marshal unmanaged data types.
In addition, this lesson comes with a sample application used for changing the display settings.
Now, we are going to discuss the required functions and structure and how to use them. After that, we will focus on the implementation code. Get ready.

EnumDisplaySettings() Function

This function resides in user32.dll. It is used to retrieve one of the modes supported by a graphics device.
The definition of this function is as following:
  1. BOOL EnumDisplaySettings(  
  2. LPCTSTR lpszDeviceName, // display device  
  3. DWORD iModeNum, // graphics mode  
  4. [In, Out] LPDEVMODE lpDevMode // graphics mode settings  
  5. );
This function accepts only three parameters:
  • lpszDeviceName:
    Specifies the display device name that will be used to retrieve its modes. This parameter can be either NULL to indicate the default device, or the name of the display device. You can enumerate display devices using the EnumDisplayDevices() function.
  • iModeNum:
    Specifies the type of information to retrieve. It could be either a mode index or one of these values:
      Retrieves current display mode.
      Retrieves current display mode stored on the registry.
  • lpDevMode:
    A reference (In/Out) parameter represents the DEVMODE object encapsulates the retrieved display mode information. The DEVMODE's dmSize member is used for input to represents the structure size, while other members are used for output.
As you might expect, to retrieve the current mode (settings) of the current display device, you will need to pass a NULL value as the lpszDeviceName parameter to indicate the current display, and the value -1 to the iModeNum parameter to indicate the current mode.
Unfortunately, EnumDisplaySettings() can return only one mode per call, and that mode is encapsulated into the DEVMODE object. To retrieve all modes (or few) supported by a display device, you need to call EnumDisplaySettings() many times specifying iModeNum as the mode index. Mode indexes start from zero. Therefore, to retrieve all modes, you will need to call the EnumDisplaySettings() function many times specifying 0 for iModeNum on the first time, and increment that index every call until EnumDisplaySettings() returns FALSE, which indicates that the previous mode was the last mode supported.
If you want to retrieve a mode (or all modes) supported by other display device, you will need to change the lpszDeviceName to the name of that device. You can get a list of all devices connected using the EnumDisplayDevices() function.
Now, it is the time for the PInvoke method. We can PInvoke this function in C# as following:
  1. [DllImport("User32.dll")]  
  2. [return: MarshalAs(UnmanagedType.Bool)]  
  3. public static extern Boolean EnumDisplaySettings(  
  4. [param: MarshalAs(UnmanagedType.LPTStr)]  
  5. string lpszDeviceName,  
  6. [param: MarshalAs(UnmanagedType.U4)]  
  7. int iModeNum,  
  8. [In, Out]  
  9. ref DEVMODE lpDevMode); 
What is Platform Invocation (PInvoke)? You already know, there is no such compatibility between managed code (.NET) and unmanaged code (Win32 API in our case.) Therefore, they cannot call each other directly. Rather, you make use of the PInvoke service to call unmanaged functions from the managed environment.
What is Marshaling? Marshaling is another service of the CLR. Again, there is no such compatibility between managed code and unmanaged code. Therefore, they cannot communicate directly. To send data between the managed client and unmanaged server, and vice versa, you will need to use marshaling to allow sending and receiving of the data. Marshaling converts managed data types to unmanaged data and vice versa.
As you suggested, now we are going to talk about the DEVMODE structure.

DEVMODE Structure

This structure encapsulates information about a printer or a display device.
This structure is fairly a complex structure, but we will try to break it down to be simple and easier to marshal.
The definition of this structure is as following:
  1. typedef struct DEVMODE {  
  2. BCHAR dmDeviceName[CCHDEVICENAME];  
  3. WORD dmSpecVersion;  
  4. WORD dmDriverVersion;  
  5. WORD dmSize;  
  6. WORD dmDriverExtra;  
  7. DWORD dmFields;  
  8. union {  
  9. struct {  
  10. short dmOrientation;  
  11. short dmPaperSize;  
  12. short dmPaperLength;  
  13. short dmPaperWidth;  
  14. short dmScale;  
  15. short dmCopies;  
  16. short dmDefaultSource;  
  17. short dmPrintQuality;  
  18. };  
  19. POINTL dmPosition;  
  20. DWORD dmDisplayOrientation;  
  21. DWORD dmDisplayFixedOutput;  
  22. };  
  23. short dmColor;  
  24. short dmDuplex;  
  25. short dmYResolution;  
  26. short dmTTOption;  
  27. short dmCollate;  
  28. BYTE dmFormName[CCHFORMNAME];  
  29. WORD dmLogPixels;  
  30. DWORD dmBitsPerPel;  
  31. DWORD dmPelsWidth;  
  32. DWORD dmPelsHeight;  
  33. union {  
  34. DWORD dmDisplayFlags;  
  35. DWORD dmNup;  
  36. }  
  37. DWORD dmDisplayFrequency;  
  38. #if(WINVER >= 0x0400)  
  39. DWORD dmICMMethod;  
  40. DWORD dmICMIntent;  
  41. DWORD dmMediaType;  
  42. DWORD dmDitherType;  
  43. DWORD dmReserved1;  
  44. DWORD dmReserved2;  
  45. #if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400)  
  46. DWORD dmPanningWidth;  
  47. DWORD dmPanningHeight;  
  48. #endif  
  49. #endif /* WINVER >= 0x0400 */  
  50. }
Really complex, Isn't it? Yeah, DEVMODE is one of the large and complex structures.
You might have noticed that two unions defined inside the structure. In addition, a structure is defined inside the first union –Notice that this structure is only available if it is a printer device. Plus, the union defined the structure also is for printer devices only. Therefore, for display devices, you can omit the structure, and define other members of the union sequentially, no additional work is required.
In addition, the last eight members are not supported by Windows NT, while the last two members are not supported by Windows ME and its ascendants. To solve this dilemma and support all versions, you can define three versions of the structure, one for Windows ME and its ascendants, one for Windows NT, and the last for Windows 2000 and higher versions. In addition, you will need to create three overloads of the function for the three structures. For simplicity, we will marshal the whole structure as for Windows 2000 and higher versions.
Notice that there are arrays that are defined with the length CCHFORMNAME which equals 32.
Last but not least, the second union of the structure defined two members inside, dmDisplayFlags and dmNup. For simplicity, we will take away the union and one of its members and define the other. Because both members are 4-bytes wide, we can omit anyone of them.
We can marshal that structure in C# as following:
  1. [StructLayout(LayoutKind.Sequential,  
  2. CharSet = CharSet.Ansi)]  
  3. public struct DEVMODE  
  4. {  
  5. // You can define the following constant  
  6. // but OUTSIDE the structure because you know  
  7. // that size and layout of the structure  
  8. // is very important  
  9. // CCHDEVICENAME = 32 = 0x50  
  10. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]  
  11. public string dmDeviceName;  
  12. // In addition you can define the last character array  
  13. // as following:  
  14. //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]  
  15. //public Char[] dmDeviceName;  
  16. // After the 32-bytes array  
  17. [MarshalAs(UnmanagedType.U2)]  
  18. public UInt16 dmSpecVersion;  
  19. [MarshalAs(UnmanagedType.U2)]  
  20. public UInt16 dmDriverVersion;  
  21. [MarshalAs(UnmanagedType.U2)]  
  22. public UInt16 dmSize;  
  23. [MarshalAs(UnmanagedType.U2)]  
  24. public UInt16 dmDriverExtra;  
  25. [MarshalAs(UnmanagedType.U4)]  
  26. public UInt32 dmFields;  
  27. public POINTL dmPosition;  
  28. [MarshalAs(UnmanagedType.U4)]  
  29. public UInt32 dmDisplayOrientation;  
  30. [MarshalAs(UnmanagedType.U4)]  
  31. public UInt32 dmDisplayFixedOutput;  
  32. [MarshalAs(UnmanagedType.I2)]  
  33. public Int16 dmColor;  
  34. [MarshalAs(UnmanagedType.I2)]  
  35. public Int16 dmDuplex;  
  36. [MarshalAs(UnmanagedType.I2)]  
  37. public Int16 dmYResolution;  
  38. [MarshalAs(UnmanagedType.I2)]  
  39. public Int16 dmTTOption;  
  40. [MarshalAs(UnmanagedType.I2)]  
  41. public Int16 dmCollate;  
  42. // CCHDEVICENAME = 32 = 0x50  
  43. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]  
  44. public string dmFormName;  
  45. // Also can be defined as  
  46. //[MarshalAs(UnmanagedType.ByValArray,  
  47. // SizeConst = 32, ArraySubType = UnmanagedType.U1)]  
  48. //public Byte[] dmFormName;  
  49. [MarshalAs(UnmanagedType.U2)]  
  50. public UInt16 dmLogPixels;  
  51. [MarshalAs(UnmanagedType.U4)]  
  52. public UInt32 dmBitsPerPel;  
  53. [MarshalAs(UnmanagedType.U4)]  
  54. public UInt32 dmPelsWidth;  
  55. [MarshalAs(UnmanagedType.U4)]  
  56. public UInt32 dmPelsHeight;  
  57. [MarshalAs(UnmanagedType.U4)]  
  58. public UInt32 dmDisplayFlags;  
  59. [MarshalAs(UnmanagedType.U4)]  
  60. public UInt32 dmDisplayFrequency;  
  61. [MarshalAs(UnmanagedType.U4)]  
  62. public UInt32 dmICMMethod;  
  63. [MarshalAs(UnmanagedType.U4)]  
  64. public UInt32 dmICMIntent;  
  65. [MarshalAs(UnmanagedType.U4)]  
  66. public UInt32 dmMediaType;  
  67. [MarshalAs(UnmanagedType.U4)]  
  68. public UInt32 dmDitherType;  
  69. [MarshalAs(UnmanagedType.U4)]  
  70. public UInt32 dmReserved1;  
  71. [MarshalAs(UnmanagedType.U4)]  
  72. public UInt32 dmReserved2;  
  73. [MarshalAs(UnmanagedType.U4)]  
  74. public UInt32 dmPanningWidth;  
  75. [MarshalAs(UnmanagedType.U4)]  
  76. public UInt32 dmPanningHeight;  
  77. } 
We will cover the PONTL structure soon.
Actually, these dozens of MarshalAsAttribute attributes are not all required. Honestly, it is not required for marshaling DWORD into UInt32 because they are counterparts. On the hand, MarshalAsAttribute attribute must be applied to arrays.
From all of those members, we are interested only in a few:
  • dmPelsWidth and dmPelsHeight:
    Represents the bounds (width and height) of the display. These values can be used also to determine whether the display orientation is portrait or landscape.
  • dmBitsPerPel:
    Represents the bit count (color system) of the display.
  • dmDisplayOrientation:
    Represents the orientation (rotation) of the display. This member can be one of these values:
    • DMDO_DEFAULT = 0
      The display is in the natural orientation. It is the default.
    • DMDO_90 = 1
      The display is rotated 90 degrees (measured clockwise) from DMDO_DEFAULT.
    • DMDO_180 = 2
      The display is rotated 180 degrees (measured clockwise) from DMDO_DEFAULT.
    • DMDO_270 = 3
      The display is rotated 270 degrees (measured clockwise) from DMDO_DEFAULT.
  • dmDisplayFrequency:
    Represents the frequency (refresh rate) of the display.

POINTL Structure

The DEVMODE's dmPosition member represents the location that display device in reference to the desktop area. It is always located at (0, 0). This member is of the structure POINTL which represents the coordinates (x and y) of a point. As you might expect, this structure is very simple. It is defined as following: 
  1. typedef struct POINTL {  
  2. LONG x;  
  3. LONG y;  
  4. } 
We can marshal this structure easily as following: 
  1. [StructLayout(LayoutKind.Sequential)]  
  2. public struct POINTL  
  3. {  
  4. [MarshalAs(UnmanagedType.I4)]  
  5. public int x;  
  6. [MarshalAs(UnmanagedType.I4)]  
  7. public int y;  
  8. }
However, for code clarity, we have a workaround. You can omit the POINTL structure and replace the dmPosition member with two members, you can call them dmPositionX and dmPositionY, and that will work fine because you know that the size and layout (position of members) of structures is very important. And doing that will not break this rule.

ChangeDisplaySettings() Function

This function resides in user32.dll. It is used to change display settings to the mode specified, but only if the mode is valid.
The definition of this function is as following 
  1. LONG ChangeDisplaySettings(  
  2. LPDEVMODE lpDevMode, // graphics mode  
  3. DWORD dwflags // graphics mode options  
  4. );
This function accepts only two arguments:
  • lpDevMode:
    A reference (In/Out) argument of the type DEVMODE represents the new settings (mode) that will be applied to the display device. After retrieving the current settings using the EnumDisplaySettings() function, you can change the desired members of the DEVMODE object and use this function to change the display device to the new settings. Again, this argument is In/Out argument which means that it is used for input and output. DEVMODE's dmSize member is used for input and other members are used for output.
  • dwflags:
    Indicates how the mode should be changed. Actually, in this example, we are not interested in this argument, so we will set it to zero. If you want more help on this argument, consult the MSDN documentation.
The return value of this function varies based on the success or failure of the settings change. This function can return one of several values including:
    Indicates that the function succeeded.
    The graphics mode is not supported.
    The display driver failed the specified graphics mode.
    The computer must be restarted for the graphics mode to work.
Consult MSDN documentation to know more about the ChangeDisplaySettings() return value. The last section of this lesson is devoted for this.
Another point of interest is that ChangeDisplaySettings() changes only the default display. If you want to change another display device, you can use the ChangeDisplaySettingsEx() function. It is very similar to ChangeDisplaySettings(). Consult MSDN documentation for more help.
Now, it is the time for creating the PInvoke method for the ChangeDisplaySettings() function.
  1. [DllImport("User32.dll")]  
  2. [return: MarshalAs(UnmanagedType.I4)]  
  3. public static extern int ChangeDisplaySettings(  
  4. [In, Out]  
  5. ref DEVMODE lpDevMode,  
  6. [param: MarshalAs(UnmanagedType.U4)]  
  7. uint dwflags); 
Now, we are going to mix things together and talk about the implementation code. Get ready.

Retrieving Current Display Mode

The code that obtains the current display settings is very easy. We use the EnumDisplaySettings() function passing it ENUM_CURRENT_SETTINGS (-1) in the iModeNum parameter to get the current settings, and NULL in the lpszDeviceName parameter to indicate the current display device.
Here is the code.
Code abbreviated for clarity.
  1. public static void GetCurrentSettings()  
  2. {  
  3. DEVMODE mode = new DEVMODE();  
  4. mode.dmSize = (ushort)Marshal.SizeOf(mode);  
  5. if (EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref mode) == true// Succeeded  
  6. {  
  7. Console.WriteLine("Current Mode:\n\t" +  
  8. "{0} by {1}, {2} bit, {3} degrees, {4} hertz",  
  9. mode.dmPelsWidth, mode.dmPelsHeight,  
  10. mode.dmBitsPerPel,  
  11. mode.dmDisplayOrientation * 90,  
  12. mode.dmDisplayFrequency);  
  13. }  
  14. }

Enumerating Supported Display Modes

As a refresher, to get the current mode or even another supported mode of the display device, you make use of the EnumDisplaySettings() function. If you pass ENUM_CURRENT_SETTINGS (-1) in the iModeNum parameter, you get the current mode. On the other hand, you can enumerate through the list of supported modes by passing the mode index in this parameter. We start by 0 which indicates the first mode, and increment it every call to enumerate through the list of the supported modes. If the function returns FALSE, that means that the mode with the index specified is not found. Therefore, the previous mode was the last one. Here is the code. 
  1. public static void EnumerateSupportedModes()  
  2. {  
  3. DEVMODE mode = new DEVMODE();  
  4. mode.dmSize = (ushort)Marshal.SizeOf(mode);  
  5. int modeIndex = 0; // 0 = The first mode  
  6. Console.WriteLine("Supported Modes:");  
  7. while (EnumDisplaySettings(null, modeIndex, ref mode) == true// Mode found  
  8. {  
  9. Console.WriteLine("\t{0} by {1}, {2} bit, {3} degrees, {4} hertz",  
  10. mode.dmPelsWidth, mode.dmPelsHeight,  
  11. mode.dmBitsPerPel,  
  12. mode.dmDisplayOrientation * 90,  
  13. mode.dmDisplayFrequency);  
  14. modeIndex++; // The next mode  
  15. }  
  16. }

Changing Display Mode

Now, we are going to change the current display settings. This can be done through the ChangeDispalySettings() function.

Changing Screen Resolution and Bit Count

The following code example loads the current settings and changes only the resolution and the bit count. Actually, you are free to change all settings or few of them that is up to you. However, for the sake of simplicity, we are going to change the screen resolution and bit count in this section, and the orientation in the next section.
  1. static void Main()  
  2. {  
  3. // Changing the display resolution  
  4. // to 800 by 600  
  5. // and the color system (bit count)  
  6. // to 16-bit  
  7. ChangeDisplaySettings(800, 600, 16);  
  8. }  
  9. public static void ChangeDisplaySettings  
  10. (int width, int height, int bitCount)  
  11. {  
  12. DEVMODE originalMode = new DEVMODE();  
  13. originalMode.dmSize =  
  14. (ushort)Marshal.SizeOf(originalMode);  
  15. // Retrieving current settings  
  16. // to edit them  
  17. EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref originalMode);  
  18. // Making a copy of the current settings  
  19. // to allow reseting to the original mode  
  20. DEVMODE newMode = originalMode;  
  21. // Changing the settings  
  22. newMode.dmPelsWidth = (uint)width;  
  23. newMode.dmPelsHeight = (uint)height;  
  24. newMode.dmBitsPerPel = (uint)bitCount;  
  25. // Capturing the operation result  
  26. int result =  
  27. ChangeDisplaySettings(ref newMode, 0);  
  28. if (result == DISP_CHANGE_SUCCESSFUL)  
  29. {  
  30. Console.WriteLine("Succeeded.\n");  
  31. // Inspecting the new mode  
  32. GetCurrentSettings();  
  33. Console.WriteLine();  
  34. // Waiting for seeing the results  
  35. Console.ReadKey(true);  
  36. ChangeDisplaySettings(ref originalMode, 0);  
  37. }  
  38. else if (result == DISP_CHANGE_BADMODE)  
  39. Console.WriteLine("Mode not supported.");  
  40. else if (result == DISP_CHANGE_RESTART)  
  41. Console.WriteLine("Restart required.");  
  42. else  
  43. Console.WriteLine("Failed. Error code = {0}", result);  
  44. } 

Changing Screen Orientation

Now we are going to change the screen orientation clockwise and anti-clockwise.
  1. static void Main()  
  2. {  
  3. // 0 degrees ( DMDO_DEFAULT = 0 )  
  4. Console.WriteLine  
  5. ("Press any key to rotate the screen . . .");  
  6. Console.ReadKey(true);  
  7. Console.WriteLine();  
  8. RotateScreen(true); // 90 degrees ( DMDO_90 = 1 )  
  9. Console.WriteLine  
  10. ("Press any key to rotate the screen . . .");  
  11. Console.ReadKey(true);  
  12. Console.WriteLine();  
  13. RotateScreen(true); // 180 degrees ( DMDO_180 = 2 )  
  14. Console.WriteLine  
  15. ("Press any key to rotate the screen . . .");  
  16. Console.ReadKey(true);  
  17. Console.WriteLine();  
  18. RotateScreen(true); // 270 degrees ( DMDO_270 = 3 )  
  19. Console.WriteLine  
  20. ("Press any key to rotate the screen . . .");  
  21. Console.ReadKey(true);  
  22. Console.WriteLine();  
  23. RotateScreen(true); // 0 degrees ( DMDO_DEFAULT = 0 )  
  24. }  
  25. public static void RotateScreen(bool clockwise)  
  26. {  
  27. // Retrieving current settings  
  28. // ...  
  29. // Rotating the screen  
  30. if (clockwise)  
  31. if (newMode.dmDisplayOrientation DMDO_DEFAULT)  
  32. newMode.dmDisplayOrientation--;  
  33. else  
  34. newMode.dmDisplayOrientation = DMDO_270;  
  35. // Swapping width and height;  
  36. uint temp = newMode.dmPelsWidth;  
  37. newMode.dmPelsWidth = newMode.dmPelsHeight;  
  38. newMode.dmPelsHeight = temp;  
  39. // Capturing the operation result  
  40. // ...  
  41. }

Sample Application

The code sample is a simple application used to change display settings and to rotate the screen.
This is a snapshot of the application:
Display Settings Sample Snapshot

The sample code is attached with the article.


It is pleasure receiving your feedbacks and comments.

Similar Articles