摘要:C#透過Windows API取得NoteBook電池使用狀況
本文出處: http://blog.blueshop.com.tw/HammerChou/archive/2006/06/21/30011.aspx
由Power Hammer兄,授權將範例由VB.NET轉為C#
以下是呼叫Windows API取得 電池使用狀況的方法
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5
6
7 namespace ConsoleApplication1
8 {
9 class Program
10 {
11 [DllImport("kernel32", EntryPoint = "GetSystemPowerStatus")]
12 private static extern void GetSystemPowerStatus(ref SYSTEM_POWER_STATUS
lpSystemPowerStatus);
13
14 public struct SYSTEM_POWER_STATUS
15 {
16 public Byte ACLineStatus; //0 = offline, 1 = Online, 255 = UnKnown Status.
17 public Byte BatteryFlag;
18 public Byte BatteryLifePercent;
19 public Byte Reserved1;
20 public int BatteryLifeTime;
21 public int BatteryFullLifeTime;
22 }
23
24 static void Main(string[] args)
25 {
26 SYSTEM_POWER_STATUS SysPower = new SYSTEM_POWER_STATUS();
27 string strLifeTime, strLifePercent;
28
29 GetSystemPowerStatus(ref SysPower);
30
31 Console.WriteLine("電力供電狀態:" + Convert.ToString(SysPower.ACLineStatus) + "\n"
32 + "估計剩餘時間:" + Convert.ToString(SysPower.BatteryLifeTime) + " seconds. \n"
33 + "估計電力剩餘:" + Convert.ToString(SysPower.BatteryLifePercent) + "% \n");
34
35 Console.ReadLine();
36 }
37 }
38 }
SYSTEM_POWER_STATUS 所傳回之狀態
The AC power status. This member can be one of the following values.
Value | Meaning |
---|---|
0 |
Offline |
1 |
Online |
255 |
Unknown status |
The battery charge status. This member can contain one or more of the following flags.
Value | Meaning |
---|---|
1 |
High—the battery capacity is at more than 66 percent |
2 |
Low—the battery capacity is at less than 33 percent |
4 |
Critical—the battery capacity is at less than five percent |
8 |
Charging |
128 |
No system battery |
255 |
Unknown status—unable to read the battery flag information |
The value is zero if the battery is not being charged and the battery capacity is between low and high.
The percentage of full battery charge remaining. This member can be a value in the range 0 to 100, or 255 if status is unknown.
Reserved; must be zero.
The number of seconds of battery life remaining, or –1 if remaining seconds are unknown.
The number of seconds of battery life when at full charge, or –1 if full battery lifetime is unknown.
各位如有不明白之處請參考:http://msdn2.microsoft.com/en-us/library/aa373232.aspx