You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#实现复制/镜像与扩展显示模式的互相切换?

C#实现多显示器复制/扩展模式切换方案

方案选择建议

如果你没有强需求必须避免调用外部进程,优先推荐直接调用displayswitch.exe,理由如下:

  • 代码实现极简,仅需要一行进程调用代码,无需处理复杂的Windows底层显示API
  • 是Windows官方原生工具,不存在兼容性问题,完美适配所有主流显卡、多显示器硬件组合
  • 执行逻辑和系统自带的投影功能完全一致,不会出现自定义API调用可能导致的显示异常、分辨率错乱等问题

调用示例代码如下:

// 切换到复制模式
System.Diagnostics.Process.Start("displayswitch.exe", "/clone");
// 切换到扩展模式
System.Diagnostics.Process.Start("displayswitch.exe", "/extend");

纯C#原生实现方案

如果确实需要纯代码实现不依赖外部进程,可以通过封装Windows CCD (显示配置核心API) 实现,以下是可直接复用的完整代码,等价于displayswitch.exe的对应命令:

适用范围:Windows 7及以上操作系统,项目架构需指定为x86或x64,避免Any CPU模式下的API调用异常

using System;
using System.Runtime.InteropServices;

public enum DisplayMode
{
    Clone,
    Extend,
    Internal,
    External
}

public static class DisplayConfigHelper
{
    [DllImport("user32.dll")]
    private static extern long SetDisplayConfig(uint numPathArrayElements, IntPtr pathArray, 
        uint numModeArrayElements, IntPtr modeArray, uint flags);

    private const uint SDC_TOPOLOGY_INTERNAL = 0x00000001;
    private const uint SDC_TOPOLOGY_CLONE = 0x00000002;
    private const uint SDC_TOPOLOGY_EXTEND = 0x00000004;
    private const uint SDC_TOPOLOGY_EXTERNAL = 0x00000008;
    private const uint SDC_APPLY = 0x00000080;

    public static void SetDisplayMode(DisplayMode mode)
    {
        uint topologyFlag = mode switch
        {
            DisplayMode.Clone => SDC_TOPOLOGY_CLONE,
            DisplayMode.Extend => SDC_TOPOLOGY_EXTEND,
            DisplayMode.Internal => SDC_TOPOLOGY_INTERNAL,
            DisplayMode.External => SDC_TOPOLOGY_EXTERNAL,
            _ => throw new ArgumentOutOfRangeException(nameof(mode))
        };
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, topologyFlag | SDC_APPLY);
    }
}

调用示例

// 切换到复制模式
DisplayConfigHelper.SetDisplayMode(DisplayMode.Clone);
// 切换到扩展模式
DisplayConfigHelper.SetDisplayMode(DisplayMode.Extend);

内容的提问来源于stack exchange,提问作者askvictor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:54:01