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

在.NET5应用中如何获取Windows系统主显示器桌面工作区域?

实现方案

完全可以实现上述需求,.NET 5及以上版本可直接通过内置的Windows Runtime API完成调用,无需手动编写PInvoke代码。

前置配置

你需要先调整项目配置适配Windows API调用:

  • 打开项目 .csproj 文件,在 <PropertyGroup> 节点中添加以下配置:
<TargetPlatformIdentifier>Windows</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.17763.0</TargetPlatformVersion>
  • 目标框架需使用 net5.0-windows 及以上版本。

需求1:获取所有显示器参数并定位主显示器

可通过 Windows.Devices.Display.DisplayMonitor 类实现,代码示例如下:

using Windows.Devices.Display;
using Windows.Devices.Enumeration;

// 获取所有显示器设备
string selector = DisplayMonitor.GetDeviceSelector();
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

foreach (DeviceInformation device in devices)
{
    DisplayMonitor monitor = await DisplayMonitor.FromIdAsync(device.Id);
    // 显示器参数获取示例
    Console.WriteLine($"显示器名称:{monitor.DisplayName}");
    Console.WriteLine($"是否为主显示器:{monitor.IsPrimary}");
    Console.WriteLine($"物理尺寸(英寸):{monitor.PhysicalSizeInInches?.Width.ToString() ?? "未知"} * {monitor.PhysicalSizeInInches?.Height.ToString() ?? "未知"}");
    Console.WriteLine($"原始分辨率:{monitor.NativeResolutionInRawPixels.Width} * {monitor.NativeResolutionInRawPixels.Height}");
    Console.WriteLine($"当前DPI:{monitor.RawDpiX}");
    
    // 定位主显示器(IsPrimary为true即为编号1的主显示器)
    if (monitor.IsPrimary)
    {
        // 保存主显示器对象供后续使用
        var primaryMonitor = monitor;
    }
}

需求2:获取主显示器WorkingArea坐标

DisplayMonitor 类已直接封装了WorkingArea的相关属性,可直接读取计算:

// 基于上方获取的主显示器对象primaryMonitor
var workAreaOffset = primaryMonitor.WorkAreaOffset;
var workAreaSize = primaryMonitor.WorkAreaSize;

// 左上角坐标
var leftTop = new { X = workAreaOffset.X, Y = workAreaOffset.Y };
// 右下角坐标
var rightBottom = new { X = workAreaOffset.X + workAreaSize.Width, Y = workAreaOffset.Y + workAreaSize.Height };

Console.WriteLine($"WorkingArea左上角坐标:({leftTop.X}, {leftTop.Y})");
Console.WriteLine($"WorkingArea右下角坐标:({rightBottom.X}, {rightBottom.Y})");

注:坐标单位为有效像素,已自动适配系统DPI缩放设置


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:21:02