1
0

brightness_windows.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //go:build windows
  2. package main
  3. import (
  4. "fmt"
  5. "syscall"
  6. "unsafe"
  7. )
  8. // 显示器亮度控制(Windows):
  9. // 1. 先用 EnumDisplayMonitors 枚举所有显示器,再用 dxva2.dll 的物理监视器接口
  10. // 读写 DDC/CI 硬件亮度(与 Twinkle 等工具同一机制);
  11. // 2. 显示器不支持 DDC/CI(如多数笔记本内屏、部分转接头)时,回退到 GDI
  12. // SetDeviceGammaRamp 压暗该显示器的输出(软件调光,不改变真实背光)。
  13. var (
  14. dxva2DLL = syscall.NewLazyDLL("dxva2.dll")
  15. procEnumDisplayMonitors = user32.NewProc("EnumDisplayMonitors")
  16. procGetMonitorInfoW = user32.NewProc("GetMonitorInfoW")
  17. procCreateDCW = gdi32.NewProc("CreateDCW")
  18. procBrightnessDeleteDC = gdi32.NewProc("DeleteDC")
  19. procSetDeviceGammaRamp = gdi32.NewProc("SetDeviceGammaRamp")
  20. procGetPhysicalMonitorCount = dxva2DLL.NewProc("GetNumberOfPhysicalMonitorsFromHMONITOR")
  21. procGetPhysicalMonitors = dxva2DLL.NewProc("GetPhysicalMonitorsFromHMONITOR")
  22. procDestroyPhysicalMonitors = dxva2DLL.NewProc("DestroyPhysicalMonitors")
  23. procGetMonitorBrightness = dxva2DLL.NewProc("GetMonitorBrightness")
  24. procSetMonitorBrightness = dxva2DLL.NewProc("SetMonitorBrightness")
  25. )
  26. // brightnessRect Win32 RECT
  27. type brightnessRect struct {
  28. left, top, right, bottom int32
  29. }
  30. // brightnessMonitorInfoEx Win32 MONITORINFOEXW
  31. type brightnessMonitorInfoEx struct {
  32. cbSize uint32
  33. rcMonitor brightnessRect
  34. rcWork brightnessRect
  35. dwFlags uint32
  36. szDevice [32]uint16 // \\.\DISPLAY1
  37. }
  38. // brightnessPhysicalMonitor Win32 PHYSICAL_MONITOR
  39. type brightnessPhysicalMonitor struct {
  40. handle syscall.Handle
  41. description [128]uint16
  42. }
  43. // brightnessMonitor 枚举过程中的一个显示器(物理监视器句柄仅在枚举期间有效)
  44. type brightnessMonitor struct {
  45. name string // 显示器描述(取不到时用设备名)
  46. device string // \\.\DISPLAY1,用于 Gamma 调光
  47. handle syscall.Handle
  48. hardware bool // 是否支持 DDC/CI 硬件亮度
  49. min, cur, max uint32
  50. count uint32
  51. pms []brightnessPhysicalMonitor
  52. }
  53. // 枚举回调:把所有 HMONITOR 收集到 *[]syscall.Handle
  54. var brightnessEnumCallback = syscall.NewCallback(func(hmon, _ uintptr, _ uintptr, data uintptr) uintptr {
  55. mons := (*[]syscall.Handle)(unsafe.Pointer(data))
  56. *mons = append(*mons, syscall.Handle(hmon))
  57. return 1 // 继续枚举
  58. })
  59. // brightnessAvailable 当前平台支持亮度调节
  60. func brightnessAvailable() bool { return true }
  61. // withBrightnessMonitors 枚举显示器并打开物理监视器,回调结束后统一释放句柄
  62. func withBrightnessMonitors(fn func([]brightnessMonitor)) {
  63. var hmons []syscall.Handle
  64. procEnumDisplayMonitors.Call(0, 0, brightnessEnumCallback, uintptr(unsafe.Pointer(&hmons)))
  65. mons := make([]brightnessMonitor, 0, len(hmons))
  66. for _, hmon := range hmons {
  67. info := brightnessMonitorInfoEx{cbSize: uint32(unsafe.Sizeof(brightnessMonitorInfoEx{}))}
  68. procGetMonitorInfoW.Call(uintptr(hmon), uintptr(unsafe.Pointer(&info)))
  69. device := syscall.UTF16ToString(info.szDevice[:])
  70. mon := brightnessMonitor{name: device, device: device}
  71. var count uint32
  72. ok, _, _ := procGetPhysicalMonitorCount.Call(uintptr(hmon), uintptr(unsafe.Pointer(&count)))
  73. if ok != 0 && count > 0 {
  74. pms := make([]brightnessPhysicalMonitor, count)
  75. ok, _, _ = procGetPhysicalMonitors.Call(uintptr(hmon), uintptr(count), uintptr(unsafe.Pointer(&pms[0])))
  76. if ok != 0 {
  77. mon.count = count
  78. mon.pms = pms
  79. // 取第一个可读亮度的物理监视器作为该显示器
  80. for i := range pms {
  81. var minV, curV, maxV uint32
  82. ok, _, _ := procGetMonitorBrightness.Call(uintptr(pms[i].handle),
  83. uintptr(unsafe.Pointer(&minV)), uintptr(unsafe.Pointer(&curV)), uintptr(unsafe.Pointer(&maxV)))
  84. if ok == 0 || maxV <= minV {
  85. continue
  86. }
  87. if name := syscall.UTF16ToString(pms[i].description[:]); name != "" {
  88. mon.name = name
  89. }
  90. mon.handle = pms[i].handle
  91. mon.hardware = true
  92. mon.min, mon.cur, mon.max = minV, curV, maxV
  93. break
  94. }
  95. }
  96. }
  97. mons = append(mons, mon)
  98. }
  99. fn(mons)
  100. for i := range mons {
  101. if mons[i].count > 0 && len(mons[i].pms) > 0 {
  102. procDestroyPhysicalMonitors.Call(uintptr(mons[i].count), uintptr(unsafe.Pointer(&mons[i].pms[0])))
  103. }
  104. }
  105. }
  106. // listMonitorBrightness 列出所有显示器及当前亮度
  107. func listMonitorBrightness() []MonitorBrightnessInfo {
  108. list := make([]MonitorBrightnessInfo, 0, 2)
  109. withBrightnessMonitors(func(mons []brightnessMonitor) {
  110. for i, mon := range mons {
  111. percent := 100
  112. if mon.hardware && mon.max > mon.min {
  113. percent = int((mon.cur - mon.min) * 100 / (mon.max - mon.min))
  114. }
  115. list = append(list, MonitorBrightnessInfo{
  116. Index: i,
  117. Name: mon.name,
  118. Percent: percent,
  119. Hardware: mon.hardware,
  120. })
  121. }
  122. })
  123. return list
  124. }
  125. // setMonitorBrightness 设置指定序号显示器的亮度;硬件失败时回退 Gamma
  126. func setMonitorBrightness(index, percent int) error {
  127. var result error
  128. valid := false
  129. withBrightnessMonitors(func(mons []brightnessMonitor) {
  130. if index < 0 || index >= len(mons) {
  131. return
  132. }
  133. valid = true
  134. mon := mons[index]
  135. if mon.hardware && mon.max > mon.min {
  136. value := mon.min + uint32(percent)*uint32(mon.max-mon.min)/100
  137. if ok, _, _ := procSetMonitorBrightness.Call(uintptr(mon.handle), uintptr(value)); ok != 0 {
  138. return
  139. }
  140. }
  141. result = applyGammaBrightness(mon.device, percent) // 不支持 DDC/CI 或写入失败时软件调光
  142. })
  143. if !valid {
  144. return fmt.Errorf("显示器序号无效")
  145. }
  146. return result
  147. }
  148. // applyGammaBrightness 用 Gamma Ramp 压暗指定显示器(percent=100 恢复原始输出)
  149. func applyGammaBrightness(device string, percent int) error {
  150. driver, err := syscall.UTF16PtrFromString("DISPLAY")
  151. if err != nil {
  152. return err
  153. }
  154. dev, err := syscall.UTF16PtrFromString(device)
  155. if err != nil {
  156. return err
  157. }
  158. dc, _, _ := procCreateDCW.Call(uintptr(unsafe.Pointer(driver)), uintptr(unsafe.Pointer(dev)), 0, 0)
  159. if dc == 0 {
  160. return fmt.Errorf("无法打开显示设备 %s", device)
  161. }
  162. defer procBrightnessDeleteDC.Call(dc) // Gamma 生效后即可释放 DC
  163. var ramp [3][256]uint16
  164. for i := 0; i < 256; i++ {
  165. v := uint32(i*257) * uint32(percent) / 100
  166. if v > 65535 {
  167. v = 65535
  168. }
  169. ramp[0][i], ramp[1][i], ramp[2][i] = uint16(v), uint16(v), uint16(v)
  170. }
  171. if ok, _, _ := procSetDeviceGammaRamp.Call(dc, uintptr(unsafe.Pointer(&ramp))); ok == 0 {
  172. return fmt.Errorf("设置 Gamma 亮度失败")
  173. }
  174. return nil
  175. }
  176. // 息屏:向所有顶层窗口广播 WM_SYSCOMMAND / SC_MONITORPOWER(2),显示器进入省电模式
  177. const (
  178. brightnessHWNDBroadcast = 0xFFFF
  179. brightnessWMSysCommand = 0x0112
  180. brightnessSCMonitorPower = 0xF170
  181. )
  182. // turnOffDisplay 关闭所有显示器背光(移动鼠标或按键即唤醒)
  183. func turnOffDisplay() error {
  184. ok, _, _ := procPostMessage.Call(brightnessHWNDBroadcast, brightnessWMSysCommand, brightnessSCMonitorPower, 2)
  185. if ok == 0 {
  186. return fmt.Errorf("息屏指令发送失败")
  187. }
  188. return nil
  189. }
  190. // restoreBrightness 启动时按保存的亮度恢复各显示器(按名称匹配)
  191. func restoreBrightness(levels map[string]int) {
  192. if len(levels) == 0 {
  193. return
  194. }
  195. withBrightnessMonitors(func(mons []brightnessMonitor) {
  196. for _, mon := range mons {
  197. percent, ok := levels[mon.name]
  198. if !ok {
  199. continue
  200. }
  201. if percent < 0 {
  202. percent = 0
  203. } else if percent > 100 {
  204. percent = 100
  205. }
  206. if mon.hardware && mon.max > mon.min {
  207. value := mon.min + uint32(percent)*uint32(mon.max-mon.min)/100
  208. if ok, _, _ := procSetMonitorBrightness.Call(uintptr(mon.handle), uintptr(value)); ok != 0 {
  209. continue
  210. }
  211. }
  212. _ = applyGammaBrightness(mon.device, percent)
  213. }
  214. })
  215. }