In Delphi 7 I'm working on a library implementing an object encapsulating information about the batteries attached to a system. It's working well, except for retrieving the serial number for the battery.
The code I am using for this call is as follows:
function TBattery.GetSerialNumber(hbat: THandle): boolean;
var
bqi: TBatteryQueryInformation;
Serial: PWideChar;
SerialSize,
dwOut: DWORD;
begin
Result := False;
if hbat <> INVALID_HANDLE_VALUE then
begin
ZeroMemory(@bqi, SizeOf(bqi));
dwOut := 0;
bqi.BatteryTag := FBatteryTag;
bqi.InformationLevel := BatterySerialNumber;
SerialSize := 2048;
GetMem(Serial, SerialSize);
try
ZeroMemory(Serial, SerialSize);
Result := DeviceIoControl(hbat, IOCTL_BATTERY_QUERY_INFORMATION, @bqi,
SizeOf(bqi), Serial, SerialSize, @dwOut, nil);
if Result then
FSerialNumber := Serial;
finally
FreeMem(Serial, SerialSize);
end;
end;
end;
Unfortunately, DeviceIoControl()
always returns False
and if I check GetLastError()
afterwards then it comes back with error 87, "the parameter is incorrect."
This doesn't make much sense, because the code works perfectly well if I simply change the InformationLevel
from BatterySerialNumber
to BatteryUniqueID
, say. Also, I've used the handle to the battery (hbat
) in other calls in the code before GetSerialNumber
and they all work fine, and I can call others after this one fails as well, so that's not the issue.
Any ideas? I'm really at a loss.
The issue it seems related to the
dwOut
variable which is passed as @dwOut, this variable represents the varlpBytesReturned
parameter of theDeviceIoControl
which is defined asSo replacing your code by
Must fix the problem.
WinAPI
Also check this code translated to delphi from this msdn entry
Enumerating Battery Devices
which can help you to detect any additional issues with your code.WMI
Finally as aside note, you can use the WMI to retrieve the same info, in this case using the
BatteryStaticData
WMI class