Home > Back-end >  Calling the winAPI function in Delphi
Calling the winAPI function in Delphi

Time:04-08

I'm taking my first steps in Delphi, I've created a small program that uses the GetSystemPowerStatus function to get battery status information.

To load the function, I used the Winapi.Windows unit.

Everything worked fine, but the EXE file after compilation took up 150 kb.

From what I understand from this post, using the Winapi.Windows unit is the cause of the increase, but I have not found how to access the GetSystemPowerStatus function without using the unit.

Is this possible, and how can it be done?

CodePudding user response:

If you don't want to use the Winapi.Windows unit, you will just have to declare the function in your own code. See Importing Functions from Libraries in Delphi's documentation.

For example:

type
  SYSTEM_POWER_STATUS = record
    ACLineStatus: Byte;
    BatteryFlag: Byte;
    BatteryLifePercent: Byte;
    SystemStatusFlag: Byte;
    BatteryLifeTime: UInt32;
    BatteryFullLifeTime: UInt32;
  end; 

function GetSystemPowerStatus(var lpSystemPowerStatus: SYSTEM_POWER_STATUS): LongBool; stdcall; external 'Kernel32';

This is similar (but different) to how the Winapi.Windows unit declares the function. The main differences being:

  • it splits the declaration and linkage of the function between the interface and implementation sections of the unit
  • it uses an alias for the record type
  • it uses aliases for Win32 data types
unit Winapi.Windows;

...

interface

...

type
  PSystemPowerStatus = ^TSystemPowerStatus;
  _SYSTEM_POWER_STATUS = record
    ACLineStatus : Byte;
    BatteryFlag : Byte;
    BatteryLifePercent : Byte;
    Reserved1 : Byte;
    BatteryLifeTime : DWORD;
    BatteryFullLifeTime : DWORD;
  end;
  {$EXTERNALSYM _SYSTEM_POWER_STATUS}
  TSystemPowerStatus = _SYSTEM_POWER_STATUS;
  SYSTEM_POWER_STATUS = _SYSTEM_POWER_STATUS;
  {$EXTERNALSYM SYSTEM_POWER_STATUS}

function GetSystemPowerStatus(var lpSystemPowerStatus: TSystemPowerStatus): BOOL; stdcall;
{$EXTERNALSYM GetSystemPowerStatus}

...

const
  ...
  kernel32  = 'kernel32.dll';
  ...

...

implementation

...
function GetSystemPowerStatus; external kernel32 name 'GetSystemPowerStatus';
...

end.
  • Related