Desktop Functions:

   Smart Device Functions:

Show Recent Changes
Subscribe (RSS)
Misc. Pages
Helpful Tools
Suggested Reading
Website TODO List
Support Forum
Download Visual Studio Add-In

Terms of Use
Privacy Policy
FormatMessage (kernel32)

C# Signature:

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:



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;

Or in VB

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

Sample Code:

Please add some!

Alternative Managed API:

Do you know one? Please contribute it!


Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

Access directly from VS:
Terms of Use
Find References
Show Printable Version