もくじ
https://qiita.com/tera1707/items/4fda73d86eded283ec4f
やりたいこと
C#アプリの中で、バッテリの充電が今どれくらいなのか?を知りたい。
やり方
WinFormのAPIを使うやり方と、UWPのAPIを使うやり方があるっぽい。
UWPのAPI版
Windows.Devices.Power 名前空間
のクラスを使う。
WPFで使うには、下記の手順が必要。
- UWPのAPIを使えるように参照を追加(こちら参照)
using Windows.Devices.Power;
を追加
usingSystem;usingWindows.Devices.Power;namespaceConsoleApp19{classProgram{staticBatteryAggBattery=Battery.AggregateBattery;staticvoidMain(string[]args){AggBattery.ReportUpdated+=AggBattery_ReportUpdated;Console.ReadLine();}privatestaticvoidAggBattery_ReportUpdated(Batterysender,objectargs){varreport=Battery.AggregateBattery.GetReport();varMaximum=Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);varValue=Convert.ToDouble(report.RemainingCapacityInMilliwattHours);varPercent=(Value/Maximum)*100;Console.WriteLine("Status is "+report.Status+" Charge is "+Percent.ToString("F2")+"% Charge Rate is "+report.ChargeRateInMilliwatts);Console.WriteLine(" DesignCapacityInMilliwattHours = "+report.DesignCapacityInMilliwattHours+" FullChargeCapacityInMilliwattHours = "+report.FullChargeCapacityInMilliwattHours+" RemainingCapacityInMilliwattHours = "+report.RemainingCapacityInMilliwattHours);}}}
WinForm版
System.Windows.Forms名前空間
のSystemInformation.PowerStatus
を使う。
staticvoidMain(string[]args){while(true){varchargeStatus=SystemInformation.PowerStatus.BatteryChargeStatus;varfullLifetime=SystemInformation.PowerStatus.BatteryFullLifetime;varpercent=SystemInformation.PowerStatus.BatteryLifePercent;varlifeRemaining=SystemInformation.PowerStatus.BatteryLifeRemaining;varpowerlineStatus=SystemInformation.PowerStatus.PowerLineStatus;Console.WriteLine("chargeStatus = "+chargeStatus+" fullLifetime = "+fullLifetime+" percent = "+percent+" lifeRemaining = "+lifeRemaining+" powerlineStatus = "+powerlineStatus);Thread.Sleep(1000);}}
参考
UWP版
Battery
クラス(バッテリーの情報を扱う)
https://docs.microsoft.com/en-us/uwp/api/windows.devices.power.battery?view=winrt-19041BatteryReport
クラス(バッテリーの状況を入れとくためのクラス)
https://docs.microsoft.com/en-us/uwp/api/Windows.Devices.Power.BatteryReport?redirectedfrom=MSDN&view=winrt-19041
Form版
SystemInformation クラス
https://docs.microsoft.com/ja-jp/dotnet/api/system.windows.forms.systeminformation?view=net-5.0
SystemInformation.PowerStatus
https://docs.microsoft.com/ja-jp/dotnet/api/system.windows.forms.systeminformation.powerstatus?view=net-5.0
※SystemInformation クラスには、システムの設定とかもろもろの情報が何でもかんでもつまってるっぽい。