//Sets the dictionary for display device public void SetupDisplay() { if (displayAndSettings == null) { displayAndSettings = new Dictionary <DisplayDevice, List <DevMode> >(); } else { displayAndSettings.Clear(); } if (devices == null) { devices = new List <DisplayDevice>(); } else { devices.Clear(); } bool error = false; //Here I am listing all DisplayDevices (Monitors) for (int devId = 0; !error; devId++) { try { DisplayDevice device = new DisplayDevice(); device.cb = Marshal.SizeOf(typeof(DisplayDevice)); //Gets list of display devies (can include printers) error = NativeMethods.EnumDisplayDevicesW(null, devId, ref device, 0) == 0; DisplayDevice monitorName = device;//.Clone(); error = NativeMethods.EnumDisplayDevicesW(monitorName.DeviceName, 0, ref monitorName, 0) == 0; if (error != true) { device.DeviceString = monitorName.DeviceString; devices.Add(device); } } catch (Exception) { error = true; } } List <DisplaySet> devicesAndModes = new List <DisplaySet>(); foreach (var device in devices) { var error1 = false; error = false; for (int i = 0; !error; i++) { try { DevMode mode = new DevMode(); //-1 get's the current display setting var result = NativeMethods.EnumDisplaySettings(device.DeviceName, -1 + i, ref mode); error = result == 0; if (!error) { //Adds new device to display and settings if not already included if (!displayAndSettings.Keys.Contains(device)) { displayAndSettings.Add(device, new List <DevMode>()); } //Checks if Screen Resolution, Refresh rate and bits per pixel are already contained within the list to remove duplicates that can show up if (!displayAndSettings[device].Where(m => m.dmPelsWidth == mode.dmPelsWidth && m.dmPelsHeight == mode.dmPelsHeight && m.dmDeviceName == mode.dmDeviceName && m.dmDisplayFrequency == mode.dmDisplayFrequency && m.dmBitsPerPel == mode.dmBitsPerPel).Any()) { Console.WriteLine(string.Format("{0}: {1}x{2} {3}hz", device.DeviceName, mode.dmPelsWidth, mode.dmPelsHeight, mode.dmDisplayFrequency)); displayAndSettings[device].Add(mode); } } if (!error1) { error1 = true; error = false; } } catch (Exception ex) { Console.WriteLine(ex.Message); error = false; } } } }
internal static extern ReturnCodes ChangeDisplaySettingsExW(string lpszDeviceName, ref DevMode lpDevMode, object hwnd, int dwFlags, object lParam);
internal static extern ReturnCodes ChangeDisplaySettingsEx(string lpszDeviceName, ref DevMode lpDevMode, IntPtr hwnd, int dwflags, IntPtr lParam);
internal static extern ReturnCodes ChangeDisplaySettings(ref DevMode lpDevMode, int dwFlags);
internal static extern int EnumDisplaySettingsW(string lpszDeviceName, int iModeNum, ref DevMode lpDevMode);
public ReturnCodes Execute(DisplayDevice device, DevMode mode) { IntPtr ptr = new IntPtr(); return(NativeMethods.ChangeDisplaySettingsEx(device.DeviceName, ref mode, ptr, 0, ptr)); }