如何在C#桌面应用中获取屏幕色彩的亮度强度?
如何在C#桌面应用中获取屏幕亮度(非像素采样方式)
系统原生API调用(推荐)
如果你不想通过采样像素获取屏幕显示内容的明暗,直接获取显示器的硬件亮度设置是最优解。Windows系统提供了Win32 API可以直接调用,通过C#的P/Invoke实现:
- 核心API:
GetMonitorBrightness与EnumDisplayMonitors,前者获取指定显示器的亮度范围与当前值,后者枚举系统中的显示器。 - 代码实现:
using System; using System.Runtime.InteropServices; public static class ScreenBrightnessHelper { [DllImport("user32.dll")] private static extern bool GetMonitorBrightness(IntPtr hMonitor, out uint minBrightness, out uint currentBrightness, out uint maxBrightness); [DllImport("user32.dll")] private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clipRect, MonitorEnumProc enumCallback, IntPtr data); private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT monitorRect, IntPtr data); [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left; public int Top; public int Right; public int Bottom; } public static uint GetCurrentBrightness() { uint currentBrightness = 0; EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (hMonitor, hdcMonitor, ref RECT rect, IntPtr data) => { uint min, max; if (GetMonitorBrightness(hMonitor, out min, out currentBrightness, out max)) { // 获取到第一个显示器亮度后停止枚举 return false; } return true; }, IntPtr.Zero); return currentBrightness; } } // 使用示例 // uint brightnessValue = ScreenBrightnessHelper.GetCurrentBrightness();
- 说明:返回值为0-100的整数,代表当前显示器的硬件亮度百分比,无需采样屏幕像素,一般用户权限即可调用。
官方封装类库
如果你不想自己写P/Invoke代码,可以使用微软官方的Microsoft.Windows.SDK.Contracts NuGet包,它封装了Win32 API的.NET友好接口,兼容性更好:
- 安装NuGet包后,通过
DisplayManager获取显示器亮度:
using Windows.Devices.Display.Core; using System.Threading.Tasks; public static async Task<uint> GetBrightnessViaSdk() { var displayManager = DisplayManager.GetForCurrentView(); var displays = await displayManager.GetCurrentDisplaysAsync(); if (displays.Count > 0) { var brightnessLevel = displays[0].GetCurrentBrightnessLevel(); // 转换为0-100的整数 return (uint)(brightnessLevel * 100); } return 0; }
- 说明:支持Windows 10 1809及以上版本,无需手动处理API调用细节。
跨平台注意事项
如果你的应用需要跨平台运行:
- macOS:可通过调用
CoreGraphics框架的API,或执行AppleScript命令获取亮度,C#可通过MacInterop类库实现。 - Linux:可通过
xrandr命令或libXrandr库获取亮度,C#可通过Process类执行系统命令,或P/Invoke调用原生库。
内容的提问来源于stack exchange,提问作者Enes Uğur
相关产品推荐
相关产品推荐

