Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


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

FormatMessage (kernel32)
 
.
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);

// the version, the sample is built upon:
[DllImport("Kernel32.dll", SetLastError=true)]
static extern uint FormatMessage( uint dwFlags, IntPtr lpSource,
   uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer,
   uint nSize, IntPtr pArguments);

// the parameters can also be passed as a string array:
[DllImport("Kernel32.dll", SetLastError=true)]
static extern uint FormatMessage( uint dwFlags, IntPtr lpSource,
   uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer,
   uint nSize, string[] 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

Private Declare Function FormatMessage Lib "Kernel32.dll" Alias "FormatMessageA" _

    (ByVal dwFlags As Integer, ByVal lpSource As IntPtr, _
         ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByVal lpBuffer As System.Text.StringBuilder, _
        ByVal nSize As Integer, ByVal Arguments As IntPtr) As Integer

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.

Not quite true: FormatMessage works just as expected. Only GetLastError/Marshal.GetLastWin32Error is affected by these side effects...

To have FormatMessage substitute %1, %2, etc. with arguments you pass it, declare FormatMessage with a string[] for the last parameter and just pass a normal C# string array. You need to include FORMAT_MESSAGE_ARGUMENT_ARRAY in the dwFlags parameter for this to work.

Tips & Tricks:

Sample Code:

    // from header files
    const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
    const uint FORMAT_MESSAGE_IGNORE_INSERTS  = 0x00000200;
    const uint FORMAT_MESSAGE_FROM_SYSTEM    = 0x00001000;

    int nLastError= Marshal.GetLastWin32Error();

    IntPtr lpMsgBuf= IntPtr.Zero;

    uint dwChars= FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        IntPtr.Zero,
        (uint)nLastError,
        0, // Default language
        ref lpMsgBuf,
        0,
        IntPtr.Zero);
    if (dwChars==0)
    {
        // Handle the error.
        int le= Marshal.GetLastWin32Error();
        return null;
    }

    string sRet= Marshal.PtrToStringAnsi(lpMsgBuf);

    // Free the buffer.
    lpMsgBuf= LocalFree( lpMsgBuf );
    return sRet;

Alternative Managed API:

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

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

Yet the sample might still be usefull for messages not provided by the system.

Or in VB

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

Documentation

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 PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions