(摘) Golang调整显示器亮度

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

在Win11下测试成功

package main

import (
	"fmt"
	"syscall"
	"unsafe"
)

var (
	user32                          = syscall.NewLazyDLL("user32.dll")
	dxva2                           = syscall.NewLazyDLL("dxva2.dll")
	getMonitorBrightness            = dxva2.NewProc("GetMonitorBrightness")
	setMonitorBrightness            = dxva2.NewProc("SetMonitorBrightness")
	destroyPhysicalMonitors         = dxva2.NewProc("DestroyPhysicalMonitors")
	getPhysicalMonitorsFromHMONITOR = dxva2.NewProc("GetPhysicalMonitorsFromHMONITOR")
	enumDisplayMonitors             = user32.NewProc("EnumDisplayMonitors")
)

type PHYSICAL_MONITOR struct {
	hPhysicalMonitor             syscall.Handle
	szPhysicalMonitorDescription [128]uint16
}

// SetBrightness 设置屏幕亮度
// percentage 应该是 0 到 100 之间的整数
func SetBrightness(percentage int) error {
	if percentage < 0 || percentage > 100 {
		return fmt.Errorf("亮度百分比应该在 0 到 100 之间")
	}

	var hMonitor syscall.Handle
	callback := syscall.NewCallback(func(handle syscall.Handle, _, _ uintptr, _ uintptr) uintptr {
		hMonitor = handle
		return 0 // 停止枚举
	})

	_, _, err := enumDisplayMonitors.Call(0, 0, callback, 0)
	if err != nil && err.Error() != "The operation completed successfully." {
		return fmt.Errorf("枚举显示器失败: %v", err)
	}

	var physicalMonitorArraySize uint32 = 1
	physicalMonitors := make([]PHYSICAL_MONITOR, physicalMonitorArraySize)

	ret, _, err := getPhysicalMonitorsFromHMONITOR.Call(
		uintptr(hMonitor),
		uintptr(physicalMonitorArraySize),
		uintptr(unsafe.Pointer(&physicalMonitors[0])),
	)
	if ret == 0 {
		return fmt.Errorf("获取物理显示器失败: %v", err)
	}

	hPhysicalMonitor := physicalMonitors[0].hPhysicalMonitor

	var minimumBrightness, currentBrightness, maximumBrightness uint32
	ret, _, err = getMonitorBrightness.Call(
		uintptr(hPhysicalMonitor),
		uintptr(unsafe.Pointer(&minimumBrightness)),
		uintptr(unsafe.Pointer(&currentBrightness)),
		uintptr(unsafe.Pointer(&maximumBrightness)),
	)
	if ret == 0 {
		return fmt.Errorf("获取显示器亮度失败: %v", err)
	}

	newBrightness := minimumBrightness + uint32((maximumBrightness-minimumBrightness)*uint32(percentage)/100)
	ret, _, err = setMonitorBrightness.Call(
		uintptr(hPhysicalMonitor),
		uintptr(newBrightness),
	)
	if ret == 0 {
		return fmt.Errorf("设置显示器亮度失败: %v", err)
	}

	// 清理资源
	destroyPhysicalMonitors.Call(uintptr(physicalMonitorArraySize), uintptr(unsafe.Pointer(&physicalMonitors[0])))

	return nil
}

func main() {
	SetBrightness(30)
	fmt.Println("屏幕亮度已设置为 30%")
}

相关文章