EvoCorp Home    Delphi::Advance

 

 

   

 

GetSystemError

Have you ever called a Win32 API function that returned an unexpected error code? You check the help files, or maybe MSDN for the meaning of the HRESULT "number". The following code shows how to convert those error codes into something semi-readable.

unit Win32Errors;
interface
uses
  SysUtils, Windows;
 
// Returns the last system error
function
GetSystemError: string; overload;
// Returns the error identified by ErrorCode
function GetSystemError(ErrorCode: HRESULT): string; overload;
 
implementation
 
function GetSystemError(ErrorCode: HRESULT): string; overload;
var MsgBuffer: pChar;
begin
  MsgBuffer := nil;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,
    nil, ErrorCode, 0, @MsgBuffer, 0, nil);
  Result := MsgBuffer;
  LocalFree(Cardinal(MsgBuffer));
end;
 
function GetSystemError: string; overload;
begin
  Result := GetSystemError(GetLastError);
end;
 
end.

 

Microsoft Internet Explorer is a registered trademark of Microsoft Corporation.