Live Chat Icon For mobile
Live Chat Icon

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

Platform: WinForms| Category: Win32

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);

Download C# sample, formatmessage.zip
Download VB.NET sample, formatmessage_VB.zip

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.