github.com/Code-Hex/battery@v1.0.0/battery_windows.go (about) 1 package battery 2 3 import ( 4 "math" 5 "syscall" 6 "unsafe" 7 ) 8 9 var ( 10 modkernel32 = syscall.NewLazyDLL("kernel32") 11 procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus") 12 ) 13 14 type SYSTEM_POWER_STATUS struct { 15 ACLineStatus byte 16 BatteryFlag byte 17 BatteryLifePercent byte 18 Reserved1 byte 19 BatteryLifeTime uint32 20 BatteryFullLifeTime uint32 21 } 22 23 func Info() (int, int, bool, error) { 24 var sps SYSTEM_POWER_STATUS 25 _, r1, err := procGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&sps))) 26 if r1 != 0 { 27 if err != nil { 28 return 0, 0, false, err 29 } 30 } 31 percent := int(sps.BatteryLifePercent) 32 var elapsed int 33 // BatteryLifeTime has MaxUint32 (2^32-1) when it cannot be detected. 34 if sps.BatteryLifeTime != math.MaxUint32 { 35 elapsed = int(float64(sps.BatteryLifeTime) / 60) 36 } 37 return percent, elapsed, sps.ACLineStatus == 1, nil 38 }