Search code examples
c#windowswinapimonitor

Enable a disabled screen using ChangeDisplaySettingsEx


I'm using WinAPI ChangeDisplaySettingsEx to switch my windows 10 screens config.
There are more than two screens, so ScreenSwitch.exe is not enough for me.

I referenced this:

https://www.codeproject.com/Articles/178027/How-to-create-a-display-switcher-for-Windows-XP?msg=3850767#xx3850767xx

and successed disable a screen in these code:

string displayName = @"\\.\DISPLAY3";
DEVMODE devMode= new DEVMODE();
devMode.dmPosition.x = 0;
devMode.dmPosition.y = 0;
devMode.dmPelsWidth = 0;
devMode.dmPelsHeight = 0;
devMode.dmFields = DEVMODE_Flags.DM_PELSHEIGHT | DEVMODE_Flags.DM_PELSWIDTH | DEVMODE_Flags.DM_POSITION;
devMode.dmSize = (ushort)Marshal.SizeOf(devMode);
ChangeDisplaySettingsEx(displayName, ref devMode, IntPtr.Zero, (int)(DeviceFlags.CDS_RESET | DeviceFlags.CDS_UPDATEREGISTRY), IntPtr.Zero);

But I can't enable screen:

...
devMode.dmPosition.x = -3840;
devMode.dmPosition.y = -1059;
devMode.dmPelsWidth = 3840;
devMode.dmPelsHeight = 2160;
...

ChangeDisplaySettingsEx got -1 result means CHANGE_FAILED

I guess that screen has disabled, so enable it need more information?

I tried save DEVMODE when the screen enabled, and send it to ChangeDisplaySettingsEx when screen disabled. Not works.

Thanks for any suggest


Solution

  • Thanks Strive Sun's answer.
    It work.

    I can't enable my "\.\DISPLAY3" directly,
    My "Screen2" will be active first, although the argument is "Screen3".
    But it can workaround easily, like this:

    enableScreen(2);
    enableScreen(3);
    disableScreen(2);
    



    I also tried use EnumDisplayDevices to get the deviceName of my monitor.
    I got "\.\DISPLAY3\Monitor0".

    But it will fail in ChangeDisplaySettingsEx, got -5 result (means BAD_PARAM).