This documentation is archived and is not being maintained.

DllImportAttribute.SetLastError Field

Indicates whether the callee calls the SetLastError Win32 API function before returning from the attributed method.

[Visual Basic]
Public SetLastError As Boolean
public bool SetLastError;
public: bool SetLastError;
public var SetLastError : Boolean;


true to indicate that the callee will call SetLastError; otherwise, false. The default is false, except in Visual Basic.

The runtime marshaler calls GetLastError and caches the value returned to prevent it from being overwritten by other API calls. You can retrieve the error code by calling GetLastWin32Error.


[Visual Basic, C#, C++] In some cases, Visual Basic developers use the DllImportAttribute, instead of using the Declare statement, to define a DLL function in managed code. Setting the SetLastError field is one of those cases.

[Visual Basic] 
Imports System.Runtime.InteropServices
Public Class Win32
    <DllImport ("user32.dll", SetLastError := False)> _
    Public Shared Function MessageBoxA (ByVal hWnd As Integer, _
        ByVal txt As String, ByVal caption As String, _
        ByVal Typ As Integer) As Integer
    End Function
End Class
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("user32.dll", SetLastError=true)]
    public static extern int MessageBoxA(int hWnd, String text, 
                             String caption, uint type);
using namespace System::Runtime::InteropServices;
typedef void* HWND;
[DllImport("user32", SetLastError=true)]
extern "C" int MessageBoxA(HWND hWnd,
                          String* pText,
                          String* pCaption,
                          unsigned int uType);

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.


Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

See Also

DllImportAttribute Class | DllImportAttribute Members | System.Runtime.InteropServices Namespace | GetLastWin32Error