Share this page 

Retrieve error from calling a Win APITag(s): WinAPI/Registry

If a Win API call fails for any reason, a return code is returned. Habitually, an error message is available. You can get it by calling the FormatMessage() function.
[local external function declaration]
FUNCTION long GetLastError() LIBRARY "kernel32" ALIAS FOR "GetLastError"
FUNCTION long FormatMessage  &
  (Long dwFlags ,ref  Any lpSource , Long dwMessageId  , &
   Long dwLanguageId  , ref String lpBuffer  , &
   Long nSize  , Long Arguments) LIBRARY "kernel32" &
     ALIAS FOR "FormatMessageA"
In the following example, we call the ShellExecute API giving it a non-existent filename. Then we can get the error message generated by the Windows API call.
[local external function declaration]
FUNCTION long ShellExecuteA( long hwnd,  string lpOperation,  &
    string lpFile, string lpParameters,  string lpDirectory,  &
    integer nShowCmd ) LIBRARY "SHELL32"
string ls_Null
long   ll_rc
string ls_err_str
long ll_last_error
Any temp

// try to execute a non-existent filename.
ll_rc = ShellExecuteA( Handle( This ), "open", &
    "", ls_Null, ls_Null, 1)

IF ll_rc > 1 THEN
   temp = 0
   ll_last_error = GetLastError()
   ls_err_str = Fill(Char(0),255)
   FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, temp, ll_last_error,&
      0, ref ls_err_str, 255, 0)
   MessageBox("error", ls_err_str)