Dealing with Win32 Errors

suggest change

When using interop methods, you can use GetLastError API to get additional information on you API calls.

DllImport Attribute SetLastError Attribute


Indicates that the callee will call SetLastError (Win32 API function).


Indicates that the callee will not call SetLastError (Win32 API function), therefore you will not get an error information.


[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr OpenMutex(uint access, bool handle, string lpName);

If you trying to open mutex which does not exist, GetLastError will return ERROR_FILE_NOT_FOUND.

var lastErrorCode = Marshal.GetLastWin32Error();

if (lastErrorCode == (uint)ERROR_FILE_NOT_FOUND)
    //Deal with error         

System Error Codes can be found here:

GetLastError API

There is a native GetLastError API which you can use as well :

[DllImport("coredll.dll", SetLastError=true)]
static extern Int32 GetLastError();

Here’s why:

Between your Win32 call which sets the error (calls SetLastError), the CLR can call other Win32 calls which could call SetLastError as well, this behavior can override your error value. In this scenario, if you call GetLastError you can obtain an invalid error.

Setting SetLastError = true, makes sure that the CLR retrieves the error code before it executes other Win32 calls.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents