Retrieving Windows system error message

The WIN API FormatMessage function (among other things) can retrieve message definition from an already-loaded module or the system's message table. The error code usually is provided by the GetLastError

WIN API function.

There's more info in Calvin Hsia's blog on how GetLastError works and why it may return incorrect results in the prior to VFP 9.0 versions: $SAMPLECODE$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

* Retrieve message definition from the system's message table.
FUNCTION WinApiErrMsg
LPARAMETERS tnErrorCode
#DEFINE FORMAT_MESSAGE_FROM_SYSTEM 0x1000
DECLARE Long FormatMessage IN kernel32 ;
	Long dwFlags, Long lpSource, Long dwMessageId, ;
	Long dwLanguageId, String  @lpBuffer, ;
	Long nSize, Long Arguments

LOCAL lcErrBuffer, lnNewErr, lnFlag, lcErrorMessage
lnFlag = FORMAT_MESSAGE_FROM_SYSTEM 
lcErrBuffer = REPL(CHR(0),1000)
lnNewErr = FormatMessage(lnFlag, 0, tnErrorCode, 0, @lcErrBuffer,500,0)
lcErrorMessage = Transform(tnErrorCode) + "    " + LEFT(lcErrBuffer, AT(CHR(0),lcErrBuffer)- 1 )
RETURN lcErrorMessage
*------------------------------------------------------------------------------------------------

* Example 
DECLARE Long DeleteFile IN WIN32API String lpFileName
DECLARE Long GetLastError IN WIN32API 
* Try to delete none-existing file to trigger an error 
lcFIle2Delete = "C:\TEMP\NoneExistingFile"
IF DeleteFile(lcFIle2Delete ) = 0
	* Error
	? WinApiErrMsg(GetLastError())
ENDIF	

Comments