FormatMessage
Synopsis
#include <windows.h>
DWORD FormatMessageW(
DWORD dwFlags,
LPCVOID lpSource,
DWORD dwMessageId,
DWORD dwLanguageId,
LPWSTR lpBuffer,
DWORD nSize,
va_list *Arguments
);
Parameters
Parameter | Description |
---|---|
dwFlags | Formatting options. You can combine values such as FORMAT_MESSAGE_ALLOCATE_BUFFER , FORMAT_MESSAGE_FROM_SYSTEM , FORMAT_MESSAGE_IGNORE_INSERTS , etc. |
lpSource | Pointer to the message source. Used only when FORMAT_MESSAGE_FROM_STRING or FORMAT_MESSAGE_FROM_HMODULE is set. |
dwMessageId | Identifier of the message to be retrieved. |
dwLanguageId | Language identifier for the message. Use MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) to get the default language. |
lpBuffer | Pointer 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. |
nSize | Maximum size of the buffer, in TCHARs. |
Arguments | Array 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
- The function can retrieve messages from the system message table resources or from a custom message table resource.
- When using
FORMAT_MESSAGE_ALLOCATE_BUFFER
, the caller must free the buffer withLocalFree
. - Insert sequences (e.g.,
%1
) are replaced by arguments supplied in theArguments
parameter. - Be cautious of buffer overruns; prefer using
FORMAT_MESSAGE_ALLOCATE_BUFFER
to let the system allocate the necessary space.
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;
}