-1

I'm trying to write some code in C# that will switch between duplicate/mirror and extend display modes. I've found some existing resources ("Extend my Windows desktop onto this monitor" programmatically and How do I enable a second monitor in C#?) that tackle similar questions, but have not been able to get them to work specifically for this problem. While I can do this by summoning displayswitch.exe, it would be nice to be able to keep it in C# (not exactly sure why; convince me otherwise?). Does anyone have any example code that performs the equivalent of displayswitch.exe /clone and displayswitch.exe /extend?

askvictor
  • 3,621
  • 4
  • 32
  • 45

1 Answers1

0

Some more digging finally yielded this post: how to set primary monitor for Windows-7, in C# which works for my purposes. I have lightly refactored that solution to use a Flags enum. More info on SetDisplayConfig: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setdisplayconfig

    [Flags]
    public enum SetDisplayConfigFlags : uint
    {
        SDC_TOPOLOGY_INTERNAL = 0x00000001,
        SDC_TOPOLOGY_CLONE = 0x00000002,
        SDC_TOPOLOGY_EXTEND = 0x00000004,
        SDC_TOPOLOGY_EXTERNAL = 0x00000008,
        SDC_APPLY = 0x00000080
    }

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    private static extern long SetDisplayConfig(uint numPathArrayElements,
        IntPtr pathArray, uint numModeArrayElements, IntPtr modeArray, SetDisplayConfigFlags flags);

    static void CloneDisplays() {
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_CLONE | SetDisplayConfigFlags.SDC_APPLY);
    }

    static void ExtendDisplays() {
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTEND | SetDisplayConfigFlags.SDC_APPLY);
    }

    static void ExternalDisplay() {
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTERNAL | SetDisplayConfigFlags.SDC_APPLY);
    }

    static void InternalDisplay() {
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_INTERNAL | SetDisplayConfigFlags.SDC_APPLY);
    }
askvictor
  • 3,621
  • 4
  • 32
  • 45