wmi的Win32_Battery类实现
其中EstimatedChargeRemaining属性返回剩余电量的百分比,EstimatedRunTime属性返回剩余时间(分钟)
其他属性参考http://msdn2.microsoft.com/en-us/library/aa394074.aspx 我写了一个示范代码返回剩余电量的百分比
首先在引用里添加System.Management 核心代码如下:
using System.Management;
....
ObjectQuery oq = new ObjectQuery("select * from Win32_Battery");
ManagementObjectSearcher mo = new ManagementObjectSearcher(oq);
ManagementObjectCollection moc = mo.Get();
foreach (ManagementObject moo in moc)
{
MessageBox.Show(moo["EstimatedChargeRemaining搜索"].ToString()+"%");
}
有时候需要监控到笔记本电池的剩余电量,调查后发现WMI对象可以搞定。

在使用WMI对象前,先要添加对System.Management的引用,然后就可以调用WMI对象。

我们使用的WMI对象是:Win32_Battery

对象参考:http://msdn.microsoft.com/zh-cn/library/aa394074(v=VS.85).aspx

代码:

ManagementClass mc = new ManagementClass("Win32_Battery");
ManagementObjectCollection moc = mc.GetInstances(); ManagementObjectCollection.ManagementObjectEnumerator mom = moc.GetEnumerator();if (mom.MoveNext()) {
Console.WriteLine("EstimatedChargeRemaining: \t{0}%", mom.Current.Properties["EstimatedChargeRemaining"].Value);}
  class Program
{
[DllImport("kernel32", EntryPoint = "GetSystemPowerStatus")]
private static extern void GetSystemPowerStatus搜索(ref SYSTEM_POWER_STATUS lpSystemPowerStatus); public struct SYSTEM_POWER_STATUS
{
public Byte ACLineStatus; //0 = offline, 1 = Online, 255 = UnKnown Status.
public Byte BatteryFlag;
public Byte BatteryLifePercent;
public Byte Reserved1;
public int BatteryLifeTime;
public int BatteryFullLifeTime;
} static void Main(string[] args)
{
SYSTEM_POWER_STATUS SysPower = new SYSTEM_POWER_STATUS();
string strLifeTime, strLifePercent; GetSystemPowerStatus(ref SysPower); Console.WriteLine("供电状态:" + Convert.ToString(SysPower.ACLineStatus) + "\n"
+ "剩余时间:" + Convert.ToString(SysPower.BatteryLifeTime) + " seconds. \n"
+ "电力剩余:" + Convert.ToString(SysPower.BatteryLifePercent) + "% \n"); Console.ReadLine();
}
}

Win32_Battery class

            9 out of 12 rated this helpful - Rate this topic                         
 

The  Win32_Battery WMI class represents a battery connected to the computer system.

The following syntax is simplified from Managed Object Format (MOF) code and includes all of the inherited properties. Properties are listed in alphabetic order, not MOF order.

Syntax

 
[Provider("CIMWin32")]class Win32_Battery : CIM_Battery
{
uint16   Availability;
uint32   BatteryRechargeTime;
uint16   BatteryStatus;
string   Caption;
uint16   Chemistry;
uint32   ConfigManagerErrorCode;
boolean  ConfigManagerUserConfig;
string   CreationClassName;
string   Description;
uint32   DesignCapacity;
uint64   DesignVoltage;
string   DeviceID;
boolean  ErrorCleared;
string   ErrorDescription;
uint16   EstimatedChargeRemaining;
uint32   EstimatedRunTime;
uint32   ExpectedBatteryLife;
uint32   ExpectedLife;
uint32   FullChargeCapacity;
datetime InstallDate;
uint32   LastErrorCode;
uint32   MaxRechargeTime;
string   Name;
string   PNPDeviceID;
uint16   PowerManagementCapabilities[];
boolean  PowerManagementSupported;
string   SmartBatteryVersion;
string   Status;
uint16   StatusInfo;
string   SystemCreationClassName;
string   SystemName;
uint32   TimeOnBattery;
uint32   TimeToFullCharge;
};

Members

The Win32_Battery class has these types of members:

Methods

The Win32_Battery class has these methods.

Method Description
Reset

Not implemented. To implement this method, see the Reset method in CIM_Battery for documentation.

SetPowerState

Not implemented. To implement this method, see the SetPowerState method in CIM_Battery for documentation.

Properties

The Win32_Battery class has these properties.

Availability
Data type: uint16
Access type: Read-only

Availability and status of the device.  Inherited from CIM_LogicalDevice.

Value Meaning
1 (0x1)

Other

2 (0x2)

Unknown

3 (0x3)

Running or Full Power

4 (0x4)

Warning

5 (0x5)

In Test

6 (0x6)

Not Applicable

7 (0x7)

Power Off

8 (0x8)

Off Line

9 (0x9)

Off Duty

10 (0xA)

Degraded

11 (0xB)

Not Installed

12 (0xC)

Install Error

13 (0xD)

Power Save - Unknown

The device is known to be in a power save mode, but its exact status is unknown.

14 (0xE)

Power Save - Low Power Mode

The device is in a power save state but still functioning, and may exhibit degraded performance.

15 (0xF)

Power Save - Standby

The device is not functioning, but could be brought to full power quickly.

16 (0x10)

Power Cycle

17 (0x11)

Power Save - Warning

The device is in a warning state, though also in a power save mode.

BatteryRechargeTime
Data type: uint32
Access type: Read-only
Qualifiers: Deprecated, Units                                                      (Minutes)                                                  

Time required to fully charge the battery. This property is not supported. BatteryRechargeTime  does not have a replacement property, and is now considered obsolete.

BatteryStatus
Data type: uint16
Access type: Read-only

Status of the battery. The value 10 (Undefined) is not valid in the CIM schema because in DMI it represents that no battery is installed. In this case, the object should not be instantiated. This property is inherited from CIM_Battery.

Value Meaning
1

The battery is discharging.

2

The system has access to AC so no battery is being discharged. However, the battery is not necessarily charging.

3

Fully Charged

4

Low

5

Critical

6

Charging

7

Charging and High

8

Charging and Low

9

Charging and Critical

10

Undefined

11

Partially Charged

Caption
Data type: string
Access type: Read-only

Short description  of the object—a one-line string. This property is inherited from CIM_ManagedSystemElement.

Chemistry
Data type: uint16
Access type: Read-only

Enumeration that describes the battery's chemistry. This property is inherited from CIM_Battery.

Value Meaning
1

Other

2

Unknown

3

Lead Acid

4

Nickel Cadmium

5

Nickel Metal Hydride

6

Lithium-ion

7

Zinc air

8

Lithium Polymer

ConfigManagerErrorCode
Data type: uint32
Access type: Read-only

Windows Configuration Manager error code.

Value Meaning
0 (0x0)

Device is working properly.

1 (0x1)

Device is not configured correctly.

2 (0x2)

Windows cannot load the driver for this device.

3 (0x3)

Driver for this device might be corrupted, or the  system may be  low on memory or other resources.

4 (0x4)

Device is not working properly. One of its drivers or the  registry might be corrupted.

5 (0x5)

Driver for the device requires a resource that Windows cannot manage.

6 (0x6)

Boot configuration for the device conflicts with other devices.

7 (0x7)

Cannot filter.

8 (0x8)

Driver loader for the device is missing.

9 (0x9)

Device is not working properly.  The controlling firmware is incorrectly reporting the resources for the device.

10 (0xA)

Device cannot start.

11 (0xB)

Device failed.

12 (0xC)

Device cannot find enough free resources to use.

13 (0xD)

Windows cannot verify the device's resources.

14 (0xE)

Device cannot work properly until the computer is restarted.

15 (0xF)

Device is not working properly due to a possible re-enumeration problem.

16 (0x10)

Windows cannot identify all of the resources that the device uses.

17 (0x11)

Device is requesting  an unknown resource type.

18 (0x12)

Device drivers must be reinstalled.

19 (0x13)

Failure using the VxD loader.

20 (0x14)

Registry might be corrupted.

21 (0x15)

System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.

22 (0x16)

Device is disabled.

23 (0x17)

System failure. If changing the device driver is ineffective, see the hardware documentation.

24 (0x18)

Device is not present,  not working properly, or does not have all of its drivers installed.

25 (0x19)

Windows is still setting up the device.

26 (0x1A)

Windows is still setting up the device.

27 (0x1B)

Device does not have valid log configuration.

28 (0x1C)

Device drivers   are not installed.

29 (0x1D)

Device is disabled.  The device firmware   did not provide  the required resources.

30 (0x1E)

Device is using an IRQ resource that another device is using.

31 (0x1F)

Device is not working properly.  Windows cannot load the  required device drivers.

ConfigManagerUserConfig
Data type: boolean
Access type: Read-only

If True, the device is using a user-defined configuration. This property is inherited from CIM_LogicalDevice.

CreationClassName
Data type: string
Access type: Read-only
Qualifiers: Key, MaxLen                                                      (256)                                                  

Name of the first concrete class that appears in the inheritance chain used in the creation of an instance. When used with the other key properties of the class, the property allows all instances of this class and its subclasses to be  identified uniquely. This property is inherited from CIM_LogicalDevice.

Description
Data type: string
Access type: Read-only

Description of the object. This property is inherited from CIM_ManagedSystemElement.

DesignCapacity
Data type: uint32
Access type: Read-only

Design capacity of the battery in milliwatt-hours. If the property is not supported, enter 0 (zero). This property is inherited from CIM_Battery.

DesignVoltage
Data type: uint64
Access type: Read-only

Design voltage of the battery in millivolts. If the attribute is not supported, enter 0 (zero). This property is inherited from CIM_Battery.

For more information about using uint64 values in scripts, see Scripting in WMI.

DeviceID
Data type: string
Access type: Read-only
Qualifiers: Key

Identifies the battery. This property is inherited from CIM_LogicalDevice.

Example: "Internal Battery"

ErrorCleared
Data type: boolean
Access type: Read-only

If True, the error reported in the LastErrorCode property is now cleared. This property is inherited from CIM_LogicalDevice.

ErrorDescription
Data type: string
Access type: Read-only

Free-form string that supplies more information about the error recorded in LastErrorCode property, and information about any corrective actions that may be taken. This property is inherited from CIM_LogicalDevice.

EstimatedChargeRemaining
Data type: uint16
Access type: Read-only

Estimate of the percentage of full charge remaining. This property is inherited from CIM_Battery.

EstimatedRunTime
Data type: uint32
Access type: Read-only

Estimate in minutes of the time to battery charge depletion under the present load conditions if the utility power is off, or lost and remains off, or a laptop is disconnected from a power source. This property is inherited from CIM_Battery.

ExpectedBatteryLife
Data type: uint32
Access type: Read-only
Qualifiers: Deprecated, Units                                                      (Minutes)                                                  

Amount of time it takes to completely drain the battery after it is fully charged. This property is no longer used and is considered obsolete.

ExpectedLife
Data type: uint32
Access type: Read-only

Battery's expected lifetime in minutes, assuming that the battery is fully charged. The property represents the total expected life of the battery, not its current remaining life, which is indicated by the EstimatedRunTime property. This property is inherited from CIM_Battery.

FullChargeCapacity
Data type: uint32
Access type: Read-only

Full charge capacity of the battery in milliwatt-hours. Comparison of the value to the DesignCapacity property determines when the battery requires replacement. A battery's end of life is typically when the FullChargeCapacity property falls below 80% of the DesignCapacity property. If the property is not supported, enter 0 (zero). This property is inherited from CIM_Battery.

InstallDate
Data type: datetime
Access type: Read-only

Date and time the object was installed. This property does not need a value to indicate that the object is installed. This property is inherited from CIM_ManagedSystemElement.

LastErrorCode
Data type: uint32
Access type: Read-only

Last error code reported by the logical device. This property is inherited from CIM_LogicalDevice.

MaxRechargeTime
Data type: uint32
Access type: Read-only

Maximum time, in minutes, to fully charge the battery. The property represents the time to recharge a fully depleted battery, not the current remaining charge time, which is indicated in the TimeToFullCharge property. This property is inherited from CIM_Battery.

Name
Data type: string
Access type: Read-only

Defines the label by which the object is known. When subclassed, the property can be overridden to be a key property. This property is inherited from CIM_ManagedSystemElement.

PNPDeviceID
Data type: string
Access type: Read-only

Windows Plug and Play device identifier of the logical device. This property is inherited from CIM_LogicalDevice.

Example: "*PNP030b"

PowerManagementCapabilities
Data type: uint16 array
Access type: Read-only

Array of the specific power-related capabilities of a logical device. This property is inherited from CIM_LogicalDevice.

Value Meaning
0 (0x0)

Unknown

1 (0x1)

Not Supported

2 (0x2)

Disabled

3 (0x3)

Enabled

The power management features are currently enabled but the exact feature set is unknown or the information is unavailable.

4 (0x4)

Power Saving Modes Entered Automatically

The device can change its power state based on usage or other criteria.

5 (0x5)

Power State Settable

The SetPowerState method is supported. This method is found on the parent CIM_LogicalDevice class and can be implemented. For more information, see Designing Managed Object Format (MOF) Classes.

6 (0x6)

Power Cycling Supported

The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle).

7 (0x7)

Timed Power-On Supported

The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle) and Time set to a specific date and time, or interval, for power-on.

PowerManagementSupported
Data type: boolean
Access type: Read-only

If True, the device can be power-managed (can be put into suspend mode, and so on). The property does not indicate that power management features are currently enabled, only that the logical device is capable of power management. This property is inherited from CIM_LogicalDevice.

SmartBatteryVersion
Data type: string
Access type: Read-only

Data Specification version number supported by the battery. If the battery does not support this function, the value should be left blank. This property is inherited from CIM_Battery.

Status
Data type: string
Access type: Read-only

Current status of the object. Various operational and nonoperational statuses can be defined. Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is online, yet the managed element is neither "OK" nor in one of the other states. This property is inherited from CIM_ManagedSystemElement.

The values are:

"OK"
"Error"
"Degraded"
"Unknown"
"Starting"
"Stopping"
"Service"
"Stressed"
"NonRecover"
"No Contact"
"Lost Comm"
StatusInfo
Data type: uint16
Access type: Read-only

State of the logical device. If this property does not apply to the logical device, the value 5 (Not Applicable) should be used. This property is inherited from CIM_LogicalDevice.

Value Meaning
1 (0x1)

Other

2 (0x2)

Unknown

3 (0x3)

Enabled

4 (0x4)

Disabled

5 (0x5)

Not Applicable

SystemCreationClassName
Data type: string
Access type: Read-only

Value of the scoping computer's CreationClassName property. This property is inherited from CIM_LogicalDevice.

SystemName
Data type: string
Access type: Read-only

Name of the scoping system. This property is inherited from CIM_LogicalDevice.

TimeOnBattery
Data type: uint32
Access type: Read-only

Elapsed time in seconds since the computer system's UPS last switched to battery power, or the time since the system or UPS was last restarted, whichever is less. If the battery is "on line", 0 (zero) is returned. This property is inherited from CIM_Battery.

TimeToFullCharge
Data type: uint32
Access type: Read-only

Remaining time to charge the battery fully in minutes at the current charging rate and usage. This property is inherited from CIM_Battery.

Remarks

The  Win32_Battery class is derived from CIM_Battery which derives from CIM_LogicalDevice.

Examples

For script code examples, see WMI Tasks for Scripts and Applications and the TechNet  ScriptCenter Script Repository.

For C++ code examples, see WMI C++ Application Examples.

Requirements

Minimum supported client

Windows XP

Minimum supported server

Windows Server 2003

Namespace

\root\CIMV2

MOF

CIMWin32.mof

DLL

CIMWin32.dll

See also

Computer System Hardware Classes

Win32_Battery class的更多相关文章

  1. WMI 硬件类简单介绍,默认打印机

    获取默认打印机: SELECT * FROM Win32_Printer WHERE Default=True 常用的几个WMI: 主板:Win32_BaseBoard http://msdn.mic ...

  2. c# 调用打印机

    1.本地打印机 //添加引用并using System.Management; public static void AvailablePrinters() { ManagementScope ms ...

  3. 【转】C#取硬盘、CPU、主板、网卡的序号 ManagementObjectSearcher

    private void button1_Click(object sender, EventArgs e) { textBox1.Text = ""; foreach (stri ...

  4. C#取硬盘、CPU、主板、网卡的序号 ManagementObjectSearcher

    原文:C#取硬盘.CPU.主板.网卡的序号 ManagementObjectSearcher private void button1_Click(object sender, EventArgs e ...

  5. 本地服务器硬件信息获取指令wmic

    获取BIOS序列号 wmic bios list full | find "SerialNumber" SerialNumber=P50168VB 获取CPUID(WIN32_PR ...

  6. C#获取当前主机硬件信息

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. [VBS]检测计算机各硬件信息

    1)批处理脚本:Rhea_HardwareInfoCollector.bat 调用VBScript脚本Rhea_HardwareInfoCollector.vbs,并将结果打印到文件Rhea_Resu ...

  8. python computer info look

    计算机信息查看-. import platform import platform def TestPlatform(): print("---------SYSTEM INFO------ ...

  9. Python 通过wmi获取Window服务器硬件信息

    通过pip install wmi安装wmi 查看cpu序列号: wmic cpu get processorid 查看主板序列号: wmic baseboard get serialnumber 查 ...

随机推荐

  1. EF中的贪婪加载和延迟加载(懒加载)

    在上一章中,我们使用了Linq对Entity Framework进行了一个查询,但是通过学习我们却发现了懒加载给我来的性能上的开销是很到的,尤其是在循环中,如果数据量不是很多的情况下还可以接受,如果数 ...

  2. The Stern-Brocot Number System(排序二进制)

    The Stern-Brocot Number System Input: standard input Output: standard output The Stern-Brocot tree i ...

  3. Swift 语言概览 -自己在Xcode6 动手写1

    原文:Swift 语言概览 -自己在Xcode6 动手写1 Swift是什么? Swift是苹果于WWDC 2014发布的编程语言,这里引用The Swift Programming Language ...

  4. 信号量机制DOWN操作和UP操作的详细说明

    DOWN操作:linux内核.信号DOWN例如,下面的操作: void down(struct semaphore *sem); //不间断 int down_interruptible(struct ...

  5. Robot Framework + appium 启动手机浏览器的两个方法(1)

    一.Open Browser启动 使用Selenium2Library的Open Browser方法,例子如下: browser=手机浏览器类型,如chrome 二.Open Application启 ...

  6. Php设计模式(三):行为型模式part2

    原文详见:http://www.ucai.cn/blogdetail/7023?mid=1&f=5 可以在线运行查看效果哦! <接上文> 5.中介者模式(Mediator) : 用 ...

  7. Windbg Extension NetExt

    Windbg Extension NetExt 摘要 : 在使用WINDBG做debugging的时候,需要一个好的工具帮助进行数据分析. 最常见的extension包括SOS, PSSCOR.  N ...

  8. .net中用Action等委托向外传递参数

    原文:.net中用Action等委托向外传递参数      一般我们可以使用ref,out达到向外传递参数目的. Action<T>是一个特殊的委托,除了常规应用.我们还可以用它来实现简单 ...

  9. Jquery页面中添加键盘按键事件,如ESC事件

    $(document).keydown(function(event){ if(event.keyCode == 38 || event.keyCode == 104){ i--; if(i<= ...

  10. CORS跨域资源共享

    CORS(跨域资源共享)跨域问题及解决 当使用ajax跨域请求时,浏览器报错:XmlHttpRequest error: Origin null is not allowed by Access-Co ...