SysUtils.SysErrorMessage return string with win1252 code page

Original Reporter info from Mantis: daniel.tecnobyte
  • Reporter name: Daniel Pereira Guimarães

Description:

ShowMessage(SysErrorMessage(GetLastError)) and RaiseLastOSError() in Windows PT-BR shows accented letters as unknown character.

Steps to reproduce:

In Windows PT-BR:

SetLastError(80);
RaiseLastOSError;

Or:

ShowMessage(SysErrorMessage(80));

Additional information:

To correct, replace:
- PChar by PWideChar
- FormatMessageA by FormatMessageW

See:

function SysErrorMessage(ErrorCode: Integer): String;
const
  MaxMsgSize = SizeOf(WideChar) * FORMAT_MESSAGE_MAX_WIDTH_MASK;
var
  MsgBuffer: PWideChar;
begin
  GetMem(MsgBuffer, MaxMsgSize);
  try
    FillChar(MsgBuffer^, MaxMsgSize, #0);
    FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
                   nil,
                   ErrorCode,
                   MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
                   MsgBuffer,               { This function allocs the memory }
                   MaxMsgSize,                         { Maximum message size }
                   nil);
    SysErrorMessage := Trim(String(UnicodeString(MsgBuffer)));
  finally
    FreeMem(MsgBuffer, MaxMsgSize);
  end;
end;

Mantis conversion info:

  • Mantis ID: 31630
  • Version: 1.6.4
  • Fixed in version: 3.1.1
  • Fixed in revision: 34220 (#e3ebaa6e),36291 (#406fb857)