基本原理:通过 GetSystemPowerStatus 这个 API 获得当前系统的电池电量信息,以1秒为间隔进行查询,查询结果保存到文件中同时输出到屏幕上。收到按键后退出。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 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(); } } } |