C# 控制多屏幕设置

时间:2024-03-07 21:35:42
private const uint SDC_APPLY = 0x00000080;

private const uint SDC_TOPOLOGY_INTERNAL = 0x00000001;

private const uint SDC_TOPOLOGY_CLONE = 0x00000002;

private const uint SDC_TOPOLOGY_EXTERNAL = 0x00000008;

private const uint SDC_TOPOLOGY_EXTEND = 0x00000004;

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

/// <summary>
/// 设置屏幕的显示模式
/// </summary>
/// <param name="type">模式(0 - 主屏  1 - 双屏复制  2 - 双屏扩展  3 - 第二屏幕</param>
/// <returns></returns>
public static void SetScreenMode(int type)
{
    uint smode;

    switch (type)
    {
        case 0:
            smode = SDC_APPLY | SDC_TOPOLOGY_INTERNAL;
            break;
        case 1:
            smode = SDC_APPLY | SDC_TOPOLOGY_CLONE;
            break;
        case 2:
            smode = SDC_APPLY | SDC_TOPOLOGY_EXTEND;
            break;
        case 3:
            smode = SDC_APPLY | SDC_TOPOLOGY_EXTERNAL;
            break;
        default:
            smode = SDC_APPLY | SDC_TOPOLOGY_INTERNAL;
            break;
    }

    SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, smode);
}

当屏幕选择了单屏幕显示或者双屏复制时,Screen.AllScreens.Length只会返回1,只有双屏幕复制时才会返回2。

参考:https://www.cnblogs.com/zzr-stdio/p/12093159.html