
Most of the Win32 API calls return extended error information when they
fail. To get this information in a sensible format, you can use the
GetLastError and FormatMessage APIs.
Add the following declarations and function to a BAS module in a VB project:
Option Explicit
Public Declare Function GetLastError _
Lib "kernel32" () As Long
Public Declare Function FormatMessage _
Lib "kernel32" Alias "FormatMessageA" _
(ByVal dwFlags As Long, _
lpSource As Any, _
ByVal dwMessageId As Long, _
ByVal dwLanguageId As Long, _
ByVal lpBuffer As String, _
ByVal nSize As Long, _
Arguments As Long) As Long
Public Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
Public Function LastSystemError() As String
'
' better system error
'
Dim sError As String * 500
Dim lErrNum As Long
Dim lErrMsg As Long
'
lErrNum = GetLastError
lErrMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, _
ByVal 0&, lErrNum, 0, sError, Len(sError), 0)
LastSystemError = Trim(sError)
'
End Function
Now place a command button on a standard VB form and call the
LastSystemError function:
Private Sub Command1_Click()
'
MsgBox LastSystemError
'
End Sub
If there was no error registered, you'll see a message saying "The
operation completed successfully."
When using this function, keep these points in mind:
1. Many API calls reset the value of GetLastError when successful, so the
function must be called immediately after the API call that failed.
2. The last error value is kept on a per-thread basis, therefore the
function must be called from the same thread as the API call that failed.
From--Duncan Jones, [Duncan_Jones@compuserve.com]

