Jan 17, 2008

Is there any way to get detailed error information for Win32 errors when using Platform Invoke?

Yes, you can use the FormatMessage Win32 API. Sample projects for C# and VB.NET are enclosed. This is how the declaration looks like:

[DllImport("Kernel32.dll")]

public static extern int FormatMessage(int flags, IntPtr source, int messageId, int languageId, StringBuilder buffer, int size, IntPtr arguments );

Called like so:

// You can call FormatMessage to get a descriptive error message

StringBuilder sbFormatMessage = new StringBuilder(1024);

retVal = Interop.FormatMessage(Interop.FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, Marshal.GetLastWin32Error(), 0, sbFormatMessage,

sbFormatMessage.Capacity, IntPtr.Zero);