| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238 |
- //go:build windows
- package main
- import (
- "fmt"
- "syscall"
- "unsafe"
- )
- // 显示器亮度控制(Windows):
- // 1. 先用 EnumDisplayMonitors 枚举所有显示器,再用 dxva2.dll 的物理监视器接口
- // 读写 DDC/CI 硬件亮度(与 Twinkle 等工具同一机制);
- // 2. 显示器不支持 DDC/CI(如多数笔记本内屏、部分转接头)时,回退到 GDI
- // SetDeviceGammaRamp 压暗该显示器的输出(软件调光,不改变真实背光)。
- var (
- dxva2DLL = syscall.NewLazyDLL("dxva2.dll")
- procEnumDisplayMonitors = user32.NewProc("EnumDisplayMonitors")
- procGetMonitorInfoW = user32.NewProc("GetMonitorInfoW")
- procCreateDCW = gdi32.NewProc("CreateDCW")
- procBrightnessDeleteDC = gdi32.NewProc("DeleteDC")
- procSetDeviceGammaRamp = gdi32.NewProc("SetDeviceGammaRamp")
- procGetPhysicalMonitorCount = dxva2DLL.NewProc("GetNumberOfPhysicalMonitorsFromHMONITOR")
- procGetPhysicalMonitors = dxva2DLL.NewProc("GetPhysicalMonitorsFromHMONITOR")
- procDestroyPhysicalMonitors = dxva2DLL.NewProc("DestroyPhysicalMonitors")
- procGetMonitorBrightness = dxva2DLL.NewProc("GetMonitorBrightness")
- procSetMonitorBrightness = dxva2DLL.NewProc("SetMonitorBrightness")
- )
- // brightnessRect Win32 RECT
- type brightnessRect struct {
- left, top, right, bottom int32
- }
- // brightnessMonitorInfoEx Win32 MONITORINFOEXW
- type brightnessMonitorInfoEx struct {
- cbSize uint32
- rcMonitor brightnessRect
- rcWork brightnessRect
- dwFlags uint32
- szDevice [32]uint16 // \\.\DISPLAY1
- }
- // brightnessPhysicalMonitor Win32 PHYSICAL_MONITOR
- type brightnessPhysicalMonitor struct {
- handle syscall.Handle
- description [128]uint16
- }
- // brightnessMonitor 枚举过程中的一个显示器(物理监视器句柄仅在枚举期间有效)
- type brightnessMonitor struct {
- name string // 显示器描述(取不到时用设备名)
- device string // \\.\DISPLAY1,用于 Gamma 调光
- handle syscall.Handle
- hardware bool // 是否支持 DDC/CI 硬件亮度
- min, cur, max uint32
- count uint32
- pms []brightnessPhysicalMonitor
- }
- // 枚举回调:把所有 HMONITOR 收集到 *[]syscall.Handle
- var brightnessEnumCallback = syscall.NewCallback(func(hmon, _ uintptr, _ uintptr, data uintptr) uintptr {
- mons := (*[]syscall.Handle)(unsafe.Pointer(data))
- *mons = append(*mons, syscall.Handle(hmon))
- return 1 // 继续枚举
- })
- // brightnessAvailable 当前平台支持亮度调节
- func brightnessAvailable() bool { return true }
- // withBrightnessMonitors 枚举显示器并打开物理监视器,回调结束后统一释放句柄
- func withBrightnessMonitors(fn func([]brightnessMonitor)) {
- var hmons []syscall.Handle
- procEnumDisplayMonitors.Call(0, 0, brightnessEnumCallback, uintptr(unsafe.Pointer(&hmons)))
- mons := make([]brightnessMonitor, 0, len(hmons))
- for _, hmon := range hmons {
- info := brightnessMonitorInfoEx{cbSize: uint32(unsafe.Sizeof(brightnessMonitorInfoEx{}))}
- procGetMonitorInfoW.Call(uintptr(hmon), uintptr(unsafe.Pointer(&info)))
- device := syscall.UTF16ToString(info.szDevice[:])
- mon := brightnessMonitor{name: device, device: device}
- var count uint32
- ok, _, _ := procGetPhysicalMonitorCount.Call(uintptr(hmon), uintptr(unsafe.Pointer(&count)))
- if ok != 0 && count > 0 {
- pms := make([]brightnessPhysicalMonitor, count)
- ok, _, _ = procGetPhysicalMonitors.Call(uintptr(hmon), uintptr(count), uintptr(unsafe.Pointer(&pms[0])))
- if ok != 0 {
- mon.count = count
- mon.pms = pms
- // 取第一个可读亮度的物理监视器作为该显示器
- for i := range pms {
- var minV, curV, maxV uint32
- ok, _, _ := procGetMonitorBrightness.Call(uintptr(pms[i].handle),
- uintptr(unsafe.Pointer(&minV)), uintptr(unsafe.Pointer(&curV)), uintptr(unsafe.Pointer(&maxV)))
- if ok == 0 || maxV <= minV {
- continue
- }
- if name := syscall.UTF16ToString(pms[i].description[:]); name != "" {
- mon.name = name
- }
- mon.handle = pms[i].handle
- mon.hardware = true
- mon.min, mon.cur, mon.max = minV, curV, maxV
- break
- }
- }
- }
- mons = append(mons, mon)
- }
- fn(mons)
- for i := range mons {
- if mons[i].count > 0 && len(mons[i].pms) > 0 {
- procDestroyPhysicalMonitors.Call(uintptr(mons[i].count), uintptr(unsafe.Pointer(&mons[i].pms[0])))
- }
- }
- }
- // listMonitorBrightness 列出所有显示器及当前亮度
- func listMonitorBrightness() []MonitorBrightnessInfo {
- list := make([]MonitorBrightnessInfo, 0, 2)
- withBrightnessMonitors(func(mons []brightnessMonitor) {
- for i, mon := range mons {
- percent := 100
- if mon.hardware && mon.max > mon.min {
- percent = int((mon.cur - mon.min) * 100 / (mon.max - mon.min))
- }
- list = append(list, MonitorBrightnessInfo{
- Index: i,
- Name: mon.name,
- Percent: percent,
- Hardware: mon.hardware,
- })
- }
- })
- return list
- }
- // setMonitorBrightness 设置指定序号显示器的亮度;硬件失败时回退 Gamma
- func setMonitorBrightness(index, percent int) error {
- var result error
- valid := false
- withBrightnessMonitors(func(mons []brightnessMonitor) {
- if index < 0 || index >= len(mons) {
- return
- }
- valid = true
- mon := mons[index]
- if mon.hardware && mon.max > mon.min {
- value := mon.min + uint32(percent)*uint32(mon.max-mon.min)/100
- if ok, _, _ := procSetMonitorBrightness.Call(uintptr(mon.handle), uintptr(value)); ok != 0 {
- return
- }
- }
- result = applyGammaBrightness(mon.device, percent) // 不支持 DDC/CI 或写入失败时软件调光
- })
- if !valid {
- return fmt.Errorf("显示器序号无效")
- }
- return result
- }
- // applyGammaBrightness 用 Gamma Ramp 压暗指定显示器(percent=100 恢复原始输出)
- func applyGammaBrightness(device string, percent int) error {
- driver, err := syscall.UTF16PtrFromString("DISPLAY")
- if err != nil {
- return err
- }
- dev, err := syscall.UTF16PtrFromString(device)
- if err != nil {
- return err
- }
- dc, _, _ := procCreateDCW.Call(uintptr(unsafe.Pointer(driver)), uintptr(unsafe.Pointer(dev)), 0, 0)
- if dc == 0 {
- return fmt.Errorf("无法打开显示设备 %s", device)
- }
- defer procBrightnessDeleteDC.Call(dc) // Gamma 生效后即可释放 DC
- var ramp [3][256]uint16
- for i := 0; i < 256; i++ {
- v := uint32(i*257) * uint32(percent) / 100
- if v > 65535 {
- v = 65535
- }
- ramp[0][i], ramp[1][i], ramp[2][i] = uint16(v), uint16(v), uint16(v)
- }
- if ok, _, _ := procSetDeviceGammaRamp.Call(dc, uintptr(unsafe.Pointer(&ramp))); ok == 0 {
- return fmt.Errorf("设置 Gamma 亮度失败")
- }
- return nil
- }
- // 息屏:向所有顶层窗口广播 WM_SYSCOMMAND / SC_MONITORPOWER(2),显示器进入省电模式
- const (
- brightnessHWNDBroadcast = 0xFFFF
- brightnessWMSysCommand = 0x0112
- brightnessSCMonitorPower = 0xF170
- )
- // turnOffDisplay 关闭所有显示器背光(移动鼠标或按键即唤醒)
- func turnOffDisplay() error {
- ok, _, _ := procPostMessage.Call(brightnessHWNDBroadcast, brightnessWMSysCommand, brightnessSCMonitorPower, 2)
- if ok == 0 {
- return fmt.Errorf("息屏指令发送失败")
- }
- return nil
- }
- // restoreBrightness 启动时按保存的亮度恢复各显示器(按名称匹配)
- func restoreBrightness(levels map[string]int) {
- if len(levels) == 0 {
- return
- }
- withBrightnessMonitors(func(mons []brightnessMonitor) {
- for _, mon := range mons {
- percent, ok := levels[mon.name]
- if !ok {
- continue
- }
- if percent < 0 {
- percent = 0
- } else if percent > 100 {
- percent = 100
- }
- if mon.hardware && mon.max > mon.min {
- value := mon.min + uint32(percent)*uint32(mon.max-mon.min)/100
- if ok, _, _ := procSetMonitorBrightness.Call(uintptr(mon.handle), uintptr(value)); ok != 0 {
- continue
- }
- }
- _ = applyGammaBrightness(mon.device, percent)
- }
- })
- }
|