作者: 轩墨玉生烟
查看: 2766|回复: 5
打印 上一主题 下一主题

[源码] 【Win32Api】使用Win32Api查看计算机的能源信息

[复制链接]
跳转到指定楼层
楼主
轩墨玉生烟 发表于 2016-5-31 05:28:18 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
查看: 2766|回复: 5
说明:
今天要祭出的源代码是和能源信息有关的,这些代码可以实现电源状态、电池电量等信息的查看。好了,不说这么多了,上车的赶快!

源代码:
[C#] 纯文本查看 复制代码
using System;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
namespace Cabinink.Writer.Cores
{
   /// <summary>
   /// 能源信息结构体
   /// </summary>
   [StructLayout(LayoutKind.Sequential)]
   public struct SPowerStatus
   {
      public byte AcLineStatus;
      public byte BatteryFlag;
      public byte BatteryLifePercent;
      public byte Reserved;
      public int BatteryLifeTime;
      public uint BatteryFullLifeTime;
   }
   /// <summary>
   /// 计算机能源信息类
   /// </summary>
   public sealed class EnergyInformation
   {
      [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
      private extern static bool GetSystemPowerStatus(SPowerStatus _ps);
      [DllImport("powrprof.dll", CharSet = CharSet.Auto, SetLastError = true)]
      private extern static uint PowerGetActiveScheme(IntPtr _usrrtpwrkey, ref IntPtr _guidpointer);
      [DllImport("powrprof.dll", CharSet = CharSet.Auto)]
      private extern static uint PowerSetActiveScheme(IntPtr _usrrtperkey, ref IntPtr _sguid);
      [DllImport("powrprof.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)]
      private extern static uint PowerReadACValueIndex(IntPtr _rtperkey, byte[] _sguid, byte[] _subgroup, byte[] _settingguid, ref IntPtr _acvalidx);
      [DllImport("powrprof.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)]
      private extern static uint PowerWriteACValueIndex(IntPtr _rtperkey, byte[] _sguid, byte[] _subgroup, byte[] _settingguid, int _acvalidx);
      [DllImport("kernel32.dll")]
      private extern static uint SetThreadExecutionState(EExecutionFlag _flags);
      [DllImport("user32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
      private extern static IntPtr RegisterPowerSettingNotification(IntPtr _recipient, ref Guid _settingguid, uint _flags);
      /// <summary>
      /// 获取AC电源的状态
      /// </summary>
      /// <returns>获取当前计算机所连接的AC电源适配器的状态。</returns>
      public static EAcPowerStatus GetAcPowerStatus()
      {
         SPowerStatus ps = new SPowerStatus();
         bool b = GetSystemPowerStatus(ps);
         EAcPowerStatus stat = EAcPowerStatus.Unknown;
         switch (ps.AcLineStatus)
         {
            case 0:
               stat = EAcPowerStatus.TurnOff;
               break;
            case 1:
               stat = EAcPowerStatus.TurnOn;
               break;
            case 255:
               stat = EAcPowerStatus.Unknown;
               break;
         }
         return stat;
      }
      /// <summary>
      /// 获取电池状态
      /// </summary>
      /// <returns>获取当前计算机所配备的电池的状态信息。</returns>
      public static EBatteryStatus GetBatteryStatus()
      {
         SPowerStatus ps = new SPowerStatus();
         bool b = GetSystemPowerStatus(ps);
         EBatteryStatus stat = EBatteryStatus.Charging;
         if (Convert.ToBoolean(ps.BatteryFlag) & Convert.ToBoolean(1)) stat = EBatteryStatus.High;
         if (Convert.ToBoolean(ps.BatteryFlag) & Convert.ToBoolean(2)) stat = EBatteryStatus.Low;
         if (Convert.ToBoolean(ps.BatteryFlag) & Convert.ToBoolean(4)) stat = EBatteryStatus.Critical;
         if (Convert.ToBoolean(ps.BatteryFlag) & Convert.ToBoolean(8)) stat = EBatteryStatus.Charging;
         if (Convert.ToBoolean(ps.BatteryFlag) & Convert.ToBoolean(128)) stat = EBatteryStatus.NoSystemBattery;
         return stat;
      }
      /// <summary>
      /// 获取电池电量
      /// </summary>
      /// <returns>获取当前计算机所配备的电池的可用电量,该操作执行后会返回一个整型数据,100表示电量已满,0表示电量归零,255则表示电池电量未知。</returns>
      public static int GetQuantityOfBattery()
      {
         SPowerStatus ps = new SPowerStatus();
         bool b = GetSystemPowerStatus(ps);
         if (ps.BatteryLifePercent == 255) throw new UnknownQuantityOfBatteryException("电池电量未知!");
         return ps.BatteryLifePercent;
      }
      /// <summary>
      /// 获取未充电时的电池可用时间
      /// </summary>
      /// <returns>获取当前计算机在未连接或者未充电的情况下的电池的电量的可用时间,单位为second。</returns>
      public static int GetBatteryLifeTime()
      {
         SPowerStatus ps = new SPowerStatus();
         bool b = GetSystemPowerStatus(ps);
         if (ps.BatteryLifeTime == -1) throw new UnknownBatteryUseTimeSpanException("电池剩余电量的使用时间暂时无法测定!");
         if (GetBatteryStatus() == EBatteryStatus.Charging) throw new UnknownBatteryUseTimeSpanException("无法查看充电状态下的电池电量使用时间!");
         return ps.BatteryLifeTime;
      }
      /// <summary>
      /// 阻止系统休眠,直到线程结束恢复休眠策略
      /// </summary>
      /// <param name="_includeDisplay">是否阻止关闭显示器</param>
      public static void PreventSleep(bool _includeDisplay)
      {
         if (_includeDisplay)
         {
            SetThreadExecutionState(EExecutionFlag.System | EExecutionFlag.Display | EExecutionFlag.Continus);
         }
         else
         {
            SetThreadExecutionState(EExecutionFlag.System | EExecutionFlag.Continus);
         }
      }
      /// <summary>
      /// 恢复系统休眠策略
      /// </summary>
      public static void ResotreSleep()
      {
         SetThreadExecutionState(EExecutionFlag.Continus);
      }
      /// <summary>
      /// 重置系统休眠计时器
      /// </summary>
      /// <param name="_includeDisplay">是否阻止关闭显示器</param>
      public static void ResetSleepTimer(bool _includeDisplay = false)
      {
         if (_includeDisplay)
         {
            SetThreadExecutionState(EExecutionFlag.System | EExecutionFlag.Display);
         }
         else
         {
            SetThreadExecutionState(EExecutionFlag.System);
         }
      }
   }
   /// <summary>
   /// 休眠机制的执行标志。只使用Continus参数时,则是恢复系统休眠策略。不使用Continus参数时,实现阻止系统休眠或显示器关闭一次。组合使用Continus参数时,实现阻止系统休眠或显示器关闭至线程终止
   /// </summary>
   [Flags()]
   public enum EExecutionFlag : uint
   {
      System = 0x1,
      Display = 0x2,
      Continus = 0x80000000u
   }
   /// <summary>
   /// AC电源的状态
   /// </summary>
   public enum EAcPowerStatus : byte
   {
      TurnOff = 0,
      TurnOn = 1,
      Unknown = 255
   }
   /// <summary>
   /// 电池状态的枚举
   /// </summary>
   public enum EBatteryStatus : byte
   {
      /// <summary>
      /// 电量充足
      /// </summary>
      High = 1,
      /// <summary>
      /// 电量较低
      /// </summary>
      Low = 2,
      /// <summary>
      /// 电量严重不足
      /// </summary>
      Critical = 4,
      /// <summary>
      /// 正在充电
      /// </summary>
      Charging = 8,
      /// <summary>
      /// 无电源
      /// </summary>
      NoSystemBattery = 128
   }
   /// <summary>
   /// 电池使用时间未知时而抛出的异常
   /// </summary>
   [Serializable]
   public class UnknownBatteryUseTimeSpanException : Exception
   {
      public UnknownBatteryUseTimeSpanException() { }
      public UnknownBatteryUseTimeSpanException(string message) : base(message) { }
      public UnknownBatteryUseTimeSpanException(string message, Exception inner) : base(message, inner) { }
      protected UnknownBatteryUseTimeSpanException(SerializationInfo info, StreamingContext context) : base(info, context) { }
   }
   /// <summary>
   /// 不清楚电池电量时而抛出的异常
   /// </summary>
   [Serializable]
   public class UnknownQuantityOfBatteryException : Exception
   {
      public UnknownQuantityOfBatteryException() { }
      public UnknownQuantityOfBatteryException(string message) : base(message) { }
      public UnknownQuantityOfBatteryException(string message, Exception inner) : base(message, inner) { }
      protected UnknownQuantityOfBatteryException(SerializationInfo info, StreamingContext context) : base(info, context) { }
   }
}


评分

参与人数 1金钱 +3 收起 理由
乔克斯 + 3 感谢分享,LZ辛苦了~

查看全部评分

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏3 转播转播
回复 论坛版权

使用道具 举报

沙发
 楼主| 轩墨玉生烟 发表于 2016-5-31 05:29:07 | 只看该作者
自顶一下,楼主辛苦了,么么哒
板凳
Tom 发表于 2016-5-31 22:34:45 | 只看该作者
满分
回复

使用道具 举报

地板
乔克斯 发表于 2016-6-2 09:34:39 | 只看该作者
不错,支持下,感谢分享~
5#
GoodSkin 发表于 2017-9-11 14:22:57 | 只看该作者
挺好用的
回复

使用道具 举报

6#
jacksonwong 发表于 2019-5-10 16:07:05 | 只看该作者
感谢分享~
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入CSkin博客

本版积分规则

QQ|申请友链|小黑屋|手机版|Archiver|CSkin ( 粤ICP备13070794号

Powered by Discuz! X3.2  © 2001-2013 Comsenz Inc.  Designed by ARTERY.cn
GMT+8, 2024-11-16 12:34, Processed in 0.554505 second(s), 29 queries , Gzip On.

快速回复 返回顶部 返回列表