MSDN Docs
Search

FormatMessage

Synopsis

#include <windows.h>

DWORD FormatMessageW(
    DWORD   dwFlags,
    LPCVOID lpSource,
    DWORD   dwMessageId,
    DWORD   dwLanguageId,
    LPWSTR  lpBuffer,
    DWORD   nSize,
    va_list *Arguments
);

Parameters

ParameterDescription
dwFlagsFormatting options. You can combine values such as FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, etc.
lpSourcePointer to the message source. Used only when FORMAT_MESSAGE_FROM_STRING or FORMAT_MESSAGE_FROM_HMODULE is set.
dwMessageIdIdentifier of the message to be retrieved.
dwLanguageIdLanguage identifier for the message. Use MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) to get the default language.
lpBufferPointer to a buffer that receives the formatted message. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this will receive a pointer to a newly allocated buffer.
nSizeMaximum size of the buffer, in TCHARs.
ArgumentsArray of inserts. Ignored if FORMAT_MESSAGE_IGNORE_INSERTS is set.

Return Value

Returns the number of TCHARs stored in the output buffer, excluding the terminating null character. If the function fails, the return value is zero. Call GetLastError for extended error information.

Remarks

Example

#include <windows.h>
#include <stdio.h>

int wmain(void)
{
    LPVOID msgBuf;
    DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS;

    DWORD size = FormatMessageW(
        flags,
        NULL,
        ERROR_FILE_NOT_FOUND,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPWSTR)&msgBuf,
        0,
        NULL);

    if (size)
    {
        wprintf(L"Error %lu: %s\n", ERROR_FILE_NOT_FOUND, (LPWSTR)msgBuf);
        LocalFree(msgBuf);
    }
    else
    {
        wprintf(L"FormatMessage failed with error %lu\n", GetLastError());
    }
    return 0;
}

See Also