Wednesday, December 17, 2008

[vb6] Get descriptions of API errors

API functions don't exactly adhere to the VB error handling scheme. Instead, they either return numeric error codes or set an error code in an internal register. To retrieve the error code of the last API error in that internal register, use the LastDllError property of the VB Err object. One thing is numeric codes, however, another thing is to get some useful description of what actually went wrong. VB does not provide that for you, but you can use the FormatMessage API to get textual description corresponding to error codes. Pass the error code to the APIerrorDescription below.
    Private Const FORMAT_MESSAGE_FROM_SYSTEM& = &H1000
Private Const FORMAT_MESSAGE_IGNORE_INSERTS& = &H200
Private 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)

Public Function APIerrorDescription(ByVal code As Long) As String
Dim msg As String, r As Long
msg = String(256, 0)
r = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM Or _
FORMAT_MESSAGE_IGNORE_INSERTS, ByVal 0, code, 0, msg, 256, ByVal 0)
If r Then APIerrorDescription = Left$(msg, r)
End Function

No comments:

Post a Comment