基本原理:通过 GetSystemPowerStatus 这个 API 获得当前系统的电池电量信息,以1秒为间隔进行查询,查询结果保存到文件中同时输出到屏幕上。收到按键后退出。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
namespace GeetBatter
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_POWER_STATUS
{
public byte ACLineStatus;
public byte BatteryFlag;
public byte BatteryLifePercent;
public byte Reserved1;
public int BatteryLifeTime;
public int BatteryFullLifeTime;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool GetSystemPowerStatus([In, Out] ref SYSTEM_POWER_STATUS systemPowerStatus);
static void Main(string[] args)
{
// The system power charger struct
SYSTEM_POWER_STATUS status = new SYSTEM_POWER_STATUS();
Boolean Running = true;
DateTime currentTime;
String Result;
String Filename = DateTime.Now.ToString("HHmmss")+".txt";
FileStream fs = new FileStream(Filename, FileMode.Append);
StreamWriter wr = new StreamWriter(fs);
while (Running)
{
Thread.Sleep(1000);
while (Console.KeyAvailable)
{
Console.ReadKey(true);
Running = false;
}
// Get Power status from Kernell
GetSystemPowerStatus(ref status);
currentTime = DateTime.Now;
Result = currentTime.ToString("HH:mm:ss") + "," + status.BatteryLifePercent;
Console.WriteLine(Result);
wr.WriteLine(Result);
}
wr.Close();
Console.WriteLine("Program would exit");
Console.ReadLine();
}
}
}