internal BatteryState() { SafeNativeMethods.SystemBatteryState battState = Power.GetSystemBatteryState(); _acOnline = battState.AcOnLine; _maxCharge = (int)battState.MaxCapacity; _currentCharge = (int)battState.RemainingCapacity; _dischargeRate = (int)battState.Rate; long _estimatedTime = (long)battState.EstimatedTime; int _minutes = (int)(_estimatedTime / 60); int _seconds = (int)(_estimatedTime % 60); _estimatedTimeRemaining = new TimeSpan(0, _minutes, _seconds); _suggestedCriticalBatteryCharge = (int)battState.DefaultAlert1; _suggestedBatteryWarningCharge = (int)battState.DefaultAlert2; }
internal static SafeNativeMethods.SystemBatteryState GetSystemBatteryState() { IntPtr status = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(SafeNativeMethods.SystemBatteryState))); uint retval = NativeMethods.CallNtPowerInformation( 5, // SystemBatteryState (IntPtr)null, 0, status, (UInt32)Marshal.SizeOf(typeof(SafeNativeMethods.SystemBatteryState)) ); if (retval == SafeNativeMethods.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException("The caller had insufficient access rights to get the system battery state."); } SafeNativeMethods.SystemBatteryState batt_status = (SafeNativeMethods.SystemBatteryState)Marshal.PtrToStructure(status, typeof(SafeNativeMethods.SystemBatteryState)); Marshal.FreeCoTaskMem(status); return(batt_status); }