13.5. Retrieve Unmanaged Error Information

Problem

You need to retrieve error information (either an error code or a text message) explaining why a Win32 API call failed.

Solution

On the declaration of the unmanaged method, set the SetLastError field of DllImportAttribute to True. If an error occurs when you execute the method, call the Shared Marshal.GetLastWin32Error method to retrieve the error code. To get a text description for a specific error code, use the unmanaged FormatMessage function.

How It Works

You cannot retrieve error information directly using the unmanaged GetLastError function. The problem is that the error code returned by GetLastError might not reflect the error caused by the unmanaged function you are using. Instead, it ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.