Use this code to get Battery State
dwResult = 1 AC State
dwResult = 3 DC State
- DWORD GetBatteryState()
- {
- #define GBS_HASBATTERY 0x1
- #define GBS_ONBATTERY 0x2
-
-
-
-
-
-
- DWORD dwResult = GBS_ONBATTERY;
-
-
- HDEVINFO hdev =
- SetupDiGetClassDevs(&GUID_DEVCLASS_BATTERY,
- 0,
- 0,
- DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
- if (INVALID_HANDLE_VALUE != hdev)
- {
-
- for (int idev = 0; idev < 100; idev++)
- {
- SP_DEVICE_INTERFACE_DATA did = {0};
- did.cbSize = sizeof(did);
- if (SetupDiEnumDeviceInterfaces(hdev,
- 0,
- &GUID_DEVCLASS_BATTERY,
- idev,
- &did))
- {
- DWORD cbRequired = 0;
- SetupDiGetDeviceInterfaceDetail(hdev,
- &did,
- 0,
- 0,
- &cbRequired,
- 0);
- if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
- {
- PSP_DEVICE_INTERFACE_DETAIL_DATA pdidd =
- (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR,
- cbRequired);
- if (pdidd)
- {
- pdidd->cbSize = sizeof(*pdidd);
- if (SetupDiGetDeviceInterfaceDetail(hdev,
- &did,
- pdidd,
- cbRequired,
- &cbRequired,
- 0))
- {
-
- HANDLE hBattery =
- CreateFile(pdidd->DevicePath,
- GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- if (INVALID_HANDLE_VALUE != hBattery)
- {
-
- BATTERY_QUERY_INFORMATION bqi = {0};
- DWORD dwWait = 0;
- DWORD dwOut;
- if (DeviceIoControl(hBattery,
- IOCTL_BATTERY_QUERY_TAG,
- &dwWait,
- sizeof(dwWait),
- &bqi.BatteryTag,
- sizeof(bqi.BatteryTag),
- &dwOut,
- NULL)
- && bqi.BatteryTag)
- {
-
- BATTERY_INFORMATION bi = {0};
- bqi.InformationLevel = BatteryInformation;
- if (DeviceIoControl(hBattery,
- IOCTL_BATTERY_QUERY_INFORMATION,
- &bqi,
- sizeof(bqi),
- &bi,
- sizeof(bi),
- &dwOut,
- NULL))
- {
-
- if (bi.Capabilities & BATTERY_SYSTEM_BATTERY)
- {
- if (!(bi.Capabilities & BATTERY_IS_SHORT_TERM))
- {
- dwResult |= GBS_HASBATTERY;
- }
-
- BATTERY_WAIT_STATUS bws = {0};
- bws.BatteryTag = bqi.BatteryTag;
- BATTERY_STATUS bs;
- if (DeviceIoControl(hBattery,
- IOCTL_BATTERY_QUERY_STATUS,
- &bws,
- sizeof(bws),
- &bs,
- sizeof(bs),
- &dwOut,
- NULL))
- {
- if (bs.PowerState & BATTERY_POWER_ON_LINE)
- {
- dwResult &= ~GBS_ONBATTERY;
- }
- }
- }
- }
- }
- CloseHandle(hBattery);
- }
- }
- LocalFree(pdidd);
- }
- }
- }
- else if (ERROR_NO_MORE_ITEMS == GetLastError())
- {
- break;
- }
- }
- SetupDiDestroyDeviceInfoList(hdev);
- }
-
-
- if (!(dwResult & GBS_HASBATTERY))
- dwResult &= ~GBS_ONBATTERY;
- return dwResult;
- }