Win10 WPF应用如何获取系统显示设置中的亮度值?
解决WPF应用中电源计划下亮度值同步问题
你的问题核心在于:WmiMonitorBrightness获取的是硬件原生支持的亮度范围与当前硬件亮度值,而Windows的电源计划(如省电模式)会动态限制系统实际允许的亮度区间,导致显示设置中的亮度值和硬件层面的数值不匹配。下面提供两种可靠的方案来获取系统显示设置中的实际亮度级别:
方案1:使用Windows Runtime API(推荐,适合WPF桌面应用)
Windows Runtime提供的Windows.Graphics.Display.DisplayInformation类可以直接获取当前系统生效的屏幕亮度,该值会自动考虑电源计划的限制。
实现步骤:
- 在WPF项目中开启WinRT支持:
- 右键项目 → 属性 → 应用程序,若目标框架是.NET 5+/.NET Core 3.1+,勾选“启用Windows运行时支持”;若使用.NET Framework,需通过NuGet安装
Microsoft.Windows.SDK.Contracts包。
- 右键项目 → 属性 → 应用程序,若目标框架是.NET 5+/.NET Core 3.1+,勾选“启用Windows运行时支持”;若使用.NET Framework,需通过NuGet安装
- 引用命名空间:
using Windows.Graphics.Display; - 获取当前亮度值:
// 获取当前视图对应的屏幕亮度(范围0.0到1.0,对应0%-100%) double systemBrightness = DisplayInformation.GetForCurrentView().ScreenBrightness; // 转换为百分比整数 int brightnessPercent = (int)(systemBrightness * 100); - 实时监听亮度变化(可选):
若需要同步系统亮度的动态调整,可订阅亮度变化事件:DisplayInformation displayInfo = DisplayInformation.GetForCurrentView(); displayInfo.ScreenBrightnessChanged += (sender, e) => { double newBrightness = displayInfo.ScreenBrightness; // 更新你的进度条控件 };
注意:
DisplayInformation.GetForCurrentView()仅返回当前应用窗口所在显示器的亮度。多显示器场景下,需结合Win32显示器枚举方法获取所有显示器的亮度。
方案2:使用Win32 API获取系统亮度
如果你更倾向于传统Win32 API,GetMonitorBrightness函数可以直接获取系统当前生效的亮度值,该值同样会考虑电源计划的限制。
实现步骤:
- 导入Win32 API函数及结构:
[DllImport("user32.dll")] private static extern bool GetMonitorBrightness(IntPtr hMonitor, out uint pdwMinimumBrightness, out uint pdwCurrentBrightness, out uint pdwMaximumBrightness); [DllImport("user32.dll")] private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData); // 定义回调委托 private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData); [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left; public int Top; public int Right; public int Bottom; } - 枚举显示器并读取亮度:
private uint _currentSystemBrightness; public void GetSystemBrightness() { EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, MonitorEnumCallback, IntPtr.Zero); } private bool MonitorEnumCallback(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData) { uint minBrightness, currentBrightness, maxBrightness; if (GetMonitorBrightness(hMonitor, out minBrightness, out currentBrightness, out maxBrightness)) { // currentBrightness即为系统当前生效的亮度值(范围通常为0-100,对应百分比) _currentSystemBrightness = currentBrightness; } return true; // 继续枚举其他显示器 }
额外补充:读取电源计划的亮度配置
如果你需要获取AC/DC模式下的亮度上限,可使用PowerReadACValueIndex和PowerReadDCValueIndex函数,相关电源设置的GUID可参考Windows官方文档(如亮度设置的GUID为GUID_CONSOLE_DISPLAY_BRIGHTNESS)。
内容的提问来源于stack exchange,提问作者shagufta syed




