Click to See Complete Forum and Search --> : Err.LastDLLError equivalent?


Clearcode
November 3rd, 2002, 10:44 AM
How can I get similar functionality to Err.LastDllError (from VB5/6) in VB.Net? I presume GetLastError api call is still suspect because of API functions that may trample on the error code being called internally by the programming language?

mhuguet
November 11th, 2002, 07:30 AM
system.Runtime.InteropServices.Marshal.GetLastWin32Error()

-Mike Huguet
Software Architects, Inc.

Clearcode
November 14th, 2002, 03:27 AM
If you declare a DLL import with the SetLastError attribute then you can get the equivalent of VB classic's :

Err.LastDllError

with

System.Runtime.InteropServices.Marshal.GetLastWin32Error


..and like in VB classic you need to call the FormatMessage API call to get a description from this error:


Public Enum Format_Message_Flags
FORMAT_MESSAGE_ALLOCATE_BUFFER = &H100
FORMAT_MESSAGE_IGNORE_INSERTS = &H200
FORMAT_MESSAGE_FROM_STRING = &H400
FORMAT_MESSAGE_FROM_HMODULE = &H800
FORMAT_MESSAGE_FROM_SYSTEM = &H1000
FORMAT_MESSAGE_ARGUMENT_ARRAY = &H2000
End Enum

Private Const MAX_MESSAGE_LENGTH = 512

<DllImport("kernel32.dll", EntryPoint:="FormatMessageA", _
CharSet:=CharSet.Ansi, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Private Function FormatMessage(ByVal dwFlags As Format_Message_Flags, ByVal lpSource As Int32, ByVal dwMessageId As Int32, ByVal dwLanguageId As Int32, ByVal lpBuffer As String, ByVal nSize As Int32, ByVal Arguments As Int32) As Int32

End Function

Public Function GetAPIErrorMessageDescription(ByVal ApiErrNumber As Int32) As String

Dim sError As New StringBuilder(MAX_MESSAGE_LENGTH)
Dim lErrorMessageLength As Int32

lErrorMessageLength = FormatMessage(Format_Message_Flags.FORMAT_MESSAGE_FROM_SYSTEM, 0, ApiErrNumber, 0, sError, sError.Capacity, &H0)
If lErrorMessageLength > 0 Then
GetAPIErrorMessageDescription = sError.ToString
End If


End Function


Thanks,
Duncan