FormatMessage (kernel32)
Last changed: -84.110.53.106

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern uint FormatMessage(uint dwFlags, IntPtr lpSource,
   uint dwMessageId, uint dwLanguageId, [Out] StringBuilder lpBuffer,
   uint nSize, IntPtr Arguments);

VB.Net Signature:

<DllImport("Kernel32.dll", EntryPoint:="FormatMessageW", SetLastError:=True, _
     CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)>
     Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
     ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
     ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
    End Function

User-Defined Types:

None.

Notes:

DO NOT P/Invoke FormatMessage ever! You are not guaranteed to get the correct error message. The reason is that several internal .NET Framework calls call onto Win32 API's which can reset the Last error. You MUST use the Win32Exception and Marshal.GetLastWin32Error as shown below.

Tips & Tricks:

This functionality is also given by System.ComponentModel.Win32Exception:

string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
Console.WriteLine(errorMessage);

Or in VB

Dim errorMessage As String = New Win32Exception(Err.LastDllError).Message
Console.WriteLine(errorMessage)

Sample Code:

Please add some!

Alternative Managed API:

Do you know one? Please contribute it!

Documentation