Windows API, DLLs and COM
32.1 Calling the Windows API
uses Winapi.Windows, Winapi.Messages, Winapi.ShellAPI;
MessageBox(0, 'Hello from WinAPI', 'Delphi', MB_OK or MB_ICONINFORMATION);
ShellExecute(0, 'open', 'https://www.embarcadero.com', nil, nil, SW_SHOWNORMAL);
var Buffer: array[0..MAX_PATH] of Char;
GetWindowsDirectory(Buffer, MAX_PATH);
Writeln(Buffer);
var Tick := GetTickCount64;
if not CopyFile(PChar(Src), PChar(Dst), False) then RaiseLastOSError;
// Declaring an external function manually
function MessageBeep(uType: UINT): BOOL; stdcall; external 'user32.dll';32.2 Creating and Using DLLs
Don't pass Delphi string/objects across DLL boundaries unless both sides share the memory manager (ShareMem/SimpleShareMem) and the same compiler version. Prefer PChar, WideString (COM-safe), interfaces, or packages (.bpl).
library MathLib;
uses System.SysUtils;
function AddNumbers(A, B: Integer): Integer; stdcall;
begin
Result := A + B;
end;
function GetVersionStr(Buffer: PChar; Size: Integer): Integer; stdcall; // pass strings safely as PChar buffers
begin
StrPLCopy(Buffer, '1.0.0', Size - 1);
Result := Length('1.0.0');
end;
exports
AddNumbers,
GetVersionStr;
begin
end.// Static import
function AddNumbers(A, B: Integer): Integer; stdcall; external 'MathLib.dll';
// Dynamic loading
type TAddFunc = function(A, B: Integer): Integer; stdcall;
var H := LoadLibrary('MathLib.dll');
if H <> 0 then
try
var Add := TAddFunc(GetProcAddress(H, 'AddNumbers'));
if Assigned(Add) then Writeln(Add(2, 3));
finally
FreeLibrary(H);
end;
// Delayed loading: function X(...): Integer; stdcall; external 'lib.dll' delayed;32.3 COM and Office Automation
Early binding: Component → Import Component → Type Library generates *_TLB.pas wrappers.
Creating COM servers: ActiveX Library + Automation Object wizards (type library editor). COM+ and DCOM (legacy).
Windows-specific: Windows services (File → New → Other → Service Application, TService), the registry, the event log, WMI, Windows Runtime (WinRT) APIs via Winapi.* units and WinRT bindings, TTaskbar, notifications (TNotificationCenter).
uses System.Win.ComObj, Winapi.ActiveX;
var Excel := CreateOleObject('Excel.Application'); // late binding via Variant
Excel.Visible := True;
var WB := Excel.Workbooks.Add;
WB.Worksheets[1].Range['A1'].Value := 'Hello from Delphi';
WB.SaveAs('C:\Temp\report.xlsx');
Excel.Quit;
// In background threads: CoInitialize(nil) ... CoUninitialize