1、先注册函数
#region 屏幕亮度
[DllImport("dxva2.dll")]
public static extern bool SetMonitorBrightness(IntPtr hMonitor, short brightness);
[DllImport("dxva2.dll")]
public static extern bool GetMonitorBrightness(IntPtr hMonitor, ref short pdwMinimumBrightness,
ref short pdwCurrentBrightness, ref short pdwMaximumBrightness);
[DllImport("dxva2.dll")]
public static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(IntPtr hMonitor,
ref uint pdwNumberOfPhysicalMonitors);
[DllImport("dxva2.dll")]
public static extern bool GetPhysicalMonitorsFromHMONITOR(IntPtr hMonitor,
uint dwPhysicalMonitorArraySize, [Out] PhysicalMonitor[] pPhysicalMonitorArray);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow([In] IntPtr hwnd, uint dwFlags);
#endregion
2、方法
/// <summary>
/// 物理常量
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PhysicalMonitor
{
public IntPtr hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szPhysicalMonitorDescription;
}
/// <summary>
/// 设置屏幕亮度
/// </summary>
/// <param name="handle">所在屏幕窗口的句柄</param>
/// <param name="brightness">亮度</param>
/// <returns></returns>
public static bool SetBrightness(IntPtr handle, short brightness)
{
if (handle == IntPtr.Zero)
{
return false;
}
uint pdwNumberOfPhysicalMonitors = uint.MinValue;
//获取屏幕所在的屏幕设备
var hMonitor = MonitorFromWindow(handle, 1);
GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, ref pdwNumberOfPhysicalMonitors);
var screen = new PhysicalMonitor[pdwNumberOfPhysicalMonitors];
GetPhysicalMonitorsFromHMONITOR(hMonitor, pdwNumberOfPhysicalMonitors, screen);
return screen.Length <= 0 ? false : SetMonitorBrightness(screen[0].hPhysicalMonitor, brightness);
}
/// <summary>
/// 得到屏幕亮度参数
/// </summary>
/// <param name="handle">所在屏幕窗口的句柄</param>
/// <param name="minBrightness">最小亮度</param>
/// <param name="currentBrightness">当前亮度</param>
/// <param name="maxBrightness">最大亮度</param>
/// <returns></returns>
public static bool GetBrightness(IntPtr handle, ref short minBrightness,
ref short currentBrightness,
ref short maxBrightness)
{
if (handle == IntPtr.Zero)
{
return false;
}
uint pdwNumberOfPhysicalMonitors = uint.MinValue;
//获取屏幕所在的屏幕设备
var hMonitor = MonitorFromWindow(handle, 1);
GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, ref pdwNumberOfPhysicalMonitors);
var screen = new PhysicalMonitor[pdwNumberOfPhysicalMonitors];
GetPhysicalMonitorsFromHMONITOR(hMonitor, pdwNumberOfPhysicalMonitors, screen);
return screen.Length <= 0 ? false : GetMonitorBrightness(screen[0].hPhysicalMonitor, ref minBrightness,
ref currentBrightness,
ref maxBrightness);
}
3、用法
DialogTool.SetBrightness(this.Handle, 45);
short minBrightness = 0;
short currentBrightness = 0;
short maxBrightness = 0;
DialogTool.GetBrightness(this.Handle,
ref minBrightness,
ref currentBrightness,
ref maxBrightness);
Trace.WriteLine($"最小:{minBrightness},当前亮度:{currentBrightness},最大亮度:{maxBrightness}");