2013/04/03

C#.Net 透過WinAPI取得電池資訊

找電池大多都用WMI方式去Select,與WMI無緣還是沒辦法撈電池資訊?
神奇的是卻可以撈到自己電腦資訊


之後又在找了幾篇相關文章,認為『C#透過Windows API取得NoteBook電池使用狀況』寫得還不錯,學習學習摟




using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    internal class Program
    {
        [DllImport("kernel32", EntryPoint = "GetSystemPowerStatus")]
        private static extern void GetSystemPowerStatus(ref _SYSTEM_POWER_STATUS systemPowerStatus);

        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;
        }

        private static void Main(string[] args)
        {
            _SYSTEM_POWER_STATUS SystemPower = new _SYSTEM_POWER_STATUS();

            GetSystemPowerStatus(ref SystemPower);

            Console.WriteLine("電力供電狀態:" + Convert.ToString(SystemPower.ACLineStatus) + "\n"
                            + "估計剩餘時間:" + Convert.ToString(SystemPower.BatteryLifeTime) + " seconds. \n"
                            + "估計電力剩餘:" + Convert.ToString(SystemPower.BatteryLifePercent) + "% \n");
            Console.Read();
        }
    }
}


筆電未接上電池使用狀況


筆電接上電池使用狀況

由上圖可見,可能因為W7電源控制版本關係,所以不利於偵測剩餘時間
不過仍可以偵測電力剩餘啪數


參考資料:
http://www.dotblogs.com.tw/dotnetfactory/archive/2008/04/10/2778.aspx
http://msdn.microsoft.com/en-us/library/aa373232.aspx