Battery level c#
Asked Answered
R

1

7

I have a method to determine battery level and kept a timer to periodically check the battery level.

   void GetBatteryLevel()
    {
        try
        {
            //Use this code in next build
            //System.Windows.Forms.PowerStatus status = System.Windows.Forms.SystemInformation.PowerStatus;

            double batteryLevel;
            ManagementObjectSearcher mos = new ManagementObjectSearcher("select EstimatedChargeRemaining from Win32_Battery");
            ManagementObjectCollection collection = mos.Get();
            foreach (ManagementObject mo in collection)
            {
                UInt16 remainingPercent = (UInt16)mo["EstimatedChargeRemaining"];
                batteryLevel            = (double)remainingPercent;
                batteryLevel            = batteryLevel / 100;
                batteryLevel            = 1.0 - batteryLevel;
                BatteryLevel            = new System.Windows.Point(0.0, batteryLevel);
            }
        }
        catch (Exception exp)
        {
            Logger.LogMessage("EXCEPTION: " + exp.StackTrace);
        }
    }

Is there a way to register for events when battery level drops or increases by 1%? I have already registered for SystemEvents.PowerModeChanged and that works fine.

Rollway answered 18/9, 2013 at 7:13 Comment(4)
You could cheat and use a control that is never added to the form, i.e have a checkbox where you can change its checked value. I'm not sure of any other wayPuli
Android provides events for Battery level decrease/increase. There must be a way in windowsRollway
and timers will effect the battery depending on the intervalRollway
I think since you already have your timer, you could just include an if statement into that to do something different if batteryLevel is different than lastBatteryLevel, like I said, there may be better ways.Puli
B
2

Short answer is from the .Net base class library no.

With that said there are power events available but these events reside in kernel32. Microsoft did attempt to give you a hook into some of these events in the SystemEvents class but unfortunately they do not tie into all of them. Looking at the Power Management API there isn't an event that tracks the battery in the way that you desire.

Power Events: http://msdn.microsoft.com/en-us/library/windows/desktop/aa373162(v=vs.85).aspx

Power Management Services has a method called GetSystemPowerStatus that will get you the information you need. If you have an understanding of working with C++ from within .Net you could query the battery information and when it changes fire your own event.

GetSystemPowerStatus: http://msdn.microsoft.com/en-us/library/windows/desktop/aa372693(v=vs.85).aspx

Bobo answered 18/9, 2013 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.