使用 C# 或 .NET 以百分比形式找出电池充电容量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8945986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:20:32  来源:igfitidea点击:

Find out battery charge capacity in percentage using C# or .NET

c#.netpower-management

提问by H Bellamy

I have an application that gets detailed system information, and I have been able to get the percent of charge remaining but not the percent of the battery itself.

我有一个可以获取详细系统信息的应用程序,我已经能够获取剩余电量的百分比,但不能获取电池本身的百分比。

Explanation: As time goes on, the battery slowly gets worse and worse, and some applications, like Dell Support Center on Laptops, display the status of the battery, not the status of the charge, which used to be 100% but now is 90%.

说明:随着时间的推移,电池慢慢变得越来越差,一些应用程序,如笔记本电脑上的戴尔支持中心,显示电池状态,而不是充电状态,以前是 100%,现在是 90 %。

How can I get this value in C# or .NET?

如何在 C# 或 .NET 中获取此值?

采纳答案by dsolimano

Don't have a laptop to test with, but I'm guessing you could use the WMI class Win32_Battery.

没有要测试的笔记本电脑,但我猜您可以使用 WMI 类Win32_Battery

It has two fields that look interesting - DesignCapacity, which tells you

它有两个看起来很有趣的字段 - DesignCapacity,它告诉你

Design capacity of the battery in milliwatt-hours.

电池的设计容量,单位为毫瓦时。

and FullChargeCapacity, which has the fascinating note that

FullChargeCapacity,其中有一个迷人的音符

Full charge capacity of the battery in milliwatt-hours. Comparison of the value to the DesignCapacity property determines when the battery requires replacement.

电池的完全充电容量(以毫瓦时为单位)。该值与 DesignCapacity 属性的比较确定何时需要更换电池。

So my guess is that you can use WMI to read these two values, and then calculate FullChargeCapacity/DesignCapacityto find the battery health percentage number.

所以我的猜测是你可以使用WMI读取这两个值,然后计算FullChargeCapacity/DesignCapacity找到电池健康百分比数字。

EDIT

编辑

Here's a brief example of accessing WMI information using C#. I first added a reference to the System.Managementassembly. Then:

下面是一个使用 C# 访问 WMI 信息的简短示例。我首先添加了对System.Management程序集的引用。然后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Management.ObjectQuery query = new ObjectQuery("Select * FROM Win32_Battery");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject mo in collection)
            {
                foreach (PropertyData property in mo.Properties)
                {
                    Console.WriteLine("Property {0}: Value is {1}", property.Name, property.Value);
                }                   
            }
        }
    }
}

Also, note that you are basically running a SQL-like query against WMI, so you can vary that if you want. Windows Management Instrumentation Query Language, or WQL, is what you want to search for to learn more about it.

另外,请注意,您基本上是针对 WMI 运行类似 SQL 的查询,因此您可以根据需要进行更改。 Windows Management Instrumentation Query Language, 或WQL, 是您要搜索以了解更多信息的内容。

Also take a look at ahawker's answer, it may end up being more helpful if WMI isn't properly capturing the battery data, as he notes.

也看看 ahawker 的回答,他指出,如果 WMI 没有正确捕获电池数据,它最终可能会更有帮助。

回答by PinnyM

You can use the System.Windows.Forms.PowerStatus class - http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.aspx

您可以使用 System.Windows.Forms.PowerStatus 类 - http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.aspx

回答by ahawker

It seems that you are looking for the values of FullChargeCapacity, DesignCapacityand CurrentCapacity. As someone who has solved this problem before, let me make a few comments.

看来您正在寻找FullChargeCapacity,DesignCapacity和的值CurrentCapacity。作为之前解决过这个问题的人,让我发表一些评论。

The first route normally taken would be through a WMI query (Win32_Battery). However, on the test laptops I ran the WMI query (Win32_Battery) against, which included multiple manufacturers, I consistently ran into the problem of FullChargeCapacityalways returning zero. Since that didn't work, I re-wrote my solution using Win32 API and was successfully able to get accurate values that way.

通常采用的第一条路线是通过 WMI 查询 ( Win32_Battery)。但是,在我Win32_Battery针对多个制造商运行 WMI 查询 ( )的测试笔记本电脑上,我始终遇到FullChargeCapacity始终返回零的问题。由于那不起作用,我使用 Win32 API 重新编写了我的解决方案,并成功地以这种方式获得了准确的值。

Hopefully, WMI will work for you. However, if you experience the same issues I did, here is a summary of the steps required for Win32API.

希望 WMI 对您有用。但是,如果您遇到与我相同的问题,这里是 Win32API 所需步骤的摘要。

  • Use SetupDiGetClassDevsto get a device handle to the battery (GUID_DEVCLASS_BATTERY).

  • Use SetupDiEnumDeviceInterfacesto get the device data (SP_DEVICE_INTERFACE_DATA).

  • Use SetupDiGetDeviceInterfaceDetailto get the device path (SP_DEVICE_INTERFACE_DETAIL_DATA).

  • Use CreateFilewith the device path to get handle to battery.

  • Use DeviceIoControlwith battery handle, IOCTL_BATTERY_QUERY_TAGto retrieve battery query info (BATTERY_QUERY_INFORMATION).

  • Use DeviceIoControlwith battery handle, IOCTL_BATTERY_QUERY_INFORMATIONand marshalled structsto to retrieve battery info (BATTERY_INFORMATION).

  • 使用SetupDiGetClassDevs可获取设备句柄电池(GUID_DEVCLASS_BATTERY)。

  • 使用SetupDiEnumDeviceInterfaces来获得设备数据(SP_DEVICE_INTERFACE_DATA)。

  • 使用SetupDiGetDeviceInterfaceDetail来获得设备路径(SP_DEVICE_INTERFACE_DETAIL_DATA)。

  • CreateFile与设备路径一起使用以获取电池的句柄。

  • 使用DeviceIoControl带电池手柄,IOCTL_BATTERY_QUERY_TAG以获取电池查询信息(BATTERY_QUERY_INFORMATION)。

  • 使用DeviceIoControl带电池手柄,IOCTL_BATTERY_QUERY_INFORMATION并整理structs到检索电池信息(BATTERY_INFORMATION)。

Also see the Enumerating Battery Devicespost on MSDN as I found that quite helpful.

另请参阅MSDN 上的Enumering Battery Devices帖子,因为我发现它很有帮助。

I can post my solution if necessary but with all the native structdefinitions, it ends up around 500 lines of code.

如有必要,我可以发布我的解决方案,但使用所有本机struct定义,它最终大约有 500 行代码。

Example source code: https://gist.github.com/ahawker/9715872

示例源代码:https: //gist.github.com/ahawker/9715872

回答by Deepak Ramesh

Simple code to get Battery Level in C#

在 C# 中获取电池电量的简单代码

protected void batteryLevel ()
{
    var filter  = new IntentFilter(Intent.ActionBatteryChanged);
    var battery = RegisterReceiver(null, filter);
    int level   = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
    int scale   = battery.GetIntExtra(BatteryManager.ExtraScale, -1);

    double level_0_to_100 = Math.Floor (level * 100D / scale);

} 

回答by frank koch

WMI worked for me (tested on 3 notebooks of different brands), but I had to use something like this:

WMI 为我工作(在 3 个不同品牌的笔记本上测试),但我不得不使用这样的东西:

new ManagementObjectSearcher(@"\localhost\root\wmi", 
        "Select FullChargedCapacity From BatteryFullChargedCapacity");
// use value of resultingInstance.Properties["FullChargedCapacity"]

new ManagementObjectSearcher(@"\localhost\root\wmi",
        "Select DesignedCapacity From BatteryStaticData");
//use value of resultingInstance2.Properties["DesignedCapacity"]

回答by user4536490

No need to unnecessary complicate things. Try something like:

无需将不必要的复杂化。尝试类似:

using System.Management;

        String batterystatus;

        PowerStatus pwr = SystemInformation.PowerStatus;
        batterystatus = SystemInformation.PowerStatus.BatteryChargeStatus.ToString();

        MessageBox.Show("battery charge status : " + batterystatus);

        String batterylife;
        batterylife = SystemInformation.PowerStatus.BatteryLifePercent.ToString();

        MessageBox.Show(batterylife);

In this way you can get all of the battery information.

通过这种方式,您可以获得所有电池信息。

回答by Adiii

PowerStatus p = SystemInformation.PowerStatus;
int a = (int)(p.BatteryLifePercent * 100);
MessageBox.Show(""+a);

回答by Monu Singh

BatteryChargeStatus.Text = SystemInformation.PowerStatus.BatteryChargeStatus.ToString(); 
BatteryFullLifetime.Text = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();    
BatteryLifePercent.Text = SystemInformation.PowerStatus.BatteryLifePercent.ToString(); 
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString(); 
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();

If you want to perform some operation just convert these string values into the integer.

如果您想执行某些操作,只需将这些字符串值转换为整数即可。

回答by Sohaib El Mediouni

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace batterie
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            showbattrie();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public void showbattrie()
        {
            PowerStatus status = SystemInformation.PowerStatus;
            textBox1.Text = status.BatteryLifePercent.ToString("P0");
        }
    }
}