大家知道,我们可以通过Start->Settings->Systems->Power来查看系统的电池情况,包括电池的类型,剩余的电量等等,如下图1所示:

Battery Status on Windows Mobile

1Windows Mobile自带的Power查看界面

    但是如果再细化到电压、温度、电流等情况的话,我们只有自己来实现了。查阅了MSDN之后发现,托管的SystemState类中,关于Power的成员如下表1所示,并没有细化到电池的电压、温度、电流情况,只有主电池、备用电池的电量高低。

1  SystemState类中Power有关的成员

PowerBatteryBackupState

Gets the current backup battery state (for example, it is low, and charging). This enumeration allows a bitwise combination of its member values.

PowerBatteryBackupStrength

Gets the remaining backup battery power level, expressed as a percentage of fully charged.

PowerBatteryState

Gets the current battery state (for example, it is low, and charging). This enumeration allows a bitwise combination of its member values.

PowerBatteryStrength

Gets the remaining battery power level, expressed as a percentage of fully charged.

    而Native方法中有一个GetSystemPowerStatusEx2,返回SYSTEM_POWER_STATUS_EX2结构体。其包含的字段如下:  

  BYTE ACLineStatus;
  BYTE BatteryFlag;
  BYTE BatteryLifePercent;
  BYTE Reserved1;
  DWORD BatteryLifeTime;
  DWORD BatteryFullLifeTime;
  BYTE Reserved2;
  BYTE BackupBatteryFlag;
  BYTE BackupBatteryLifePercent;
  BYTE Reserved3;
  DWORD BackupBatteryLifeTime;
  DWORD BackupBatteryFullLifeTime;
  DWORD BatteryVoltage;
  DWORD BatteryCurrent;
  DWORD BatteryAverageCurrent;
  DWORD BatteryAverageInterval;
  DWORD BatterymAHourConsumed;
  DWORD BatteryTemperature;
  DWORD BackupBatteryVoltage;
  BYTE BatteryChemistry;

    在该结构体中,包括我们所需的电池电压、温度、电流情况。那么,如何来实现呢?Joel Ivory JohnsonWindows Mobile Power Management给出了实现方法。

    首先,我们将所需要的Native Method通过Platform invoke的方式引入到我们的工程中,

)]

        public static extern int GetSystemPowerStatusEx2(

             SYSTEM_POWER_STATUS_EX2 statusInfo, 

            
int length,

            
int getLatest

                );

        
public static SYSTEM_POWER_STATUS_EX2 GetSystemPowerStatus()

        {

            SYSTEM_POWER_STATUS_EX2 retVal 
= new SYSTEM_POWER_STATUS_EX2();

           
int result =  GetSystemPowerStatusEx2( retVal, Marshal.SizeOf(retVal) , 1);

            
return retVal;

        }

    然后在我们的应用逻辑中,加入GetSystemPowerStatus()函数,并且将结果显示在界面上。程序运行效果如下图2所示:

Battery Status on Windows Mobile

图2:程序运行效果

    我们可以改变模拟器的电池状态来看看程序的运行情况,如下图3所示,改变Emulator Properties中的Battery

Battery Status on Windows Mobile

3:改变Emulator Properties中的Battery

    再看程序的运行界面如下图4所示:

Battery Status on Windows Mobile

4:改变Battery后的程序界面

    可以看到,电池的剩余电量部分发生了改变,与我们设置的值相等。不过,由于我使用的是模拟器,所以电压、电流等显示有问题。在我的真实设备上,程序运行的界面如下图5所示:

Battery Status on Windows Mobile  

5:Cingular8125上的程序界面

源代码工程在此下载:BatteryStatus.rar  环境: Visual Studio 2008+Windows mobile 6.0 professional SDK

 

参考文章: Windows Mobile Power Management

相关文章: