Retrieves a system error message or a formatted message from a message file.
DWORD FormatMessage( DWORD dwFlags, _In_opt_ const LPVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, _Out_writes_autoprefixer_ LPSTR lpBuffer, DWORD nSize, _In_opt_ va_list* Arguments );
dwFlags
parameter.
lpBuffer
, in characters. If this parameter is zero, the function allocates memory for the buffer and updates the lpBuffer
parameter to a pointer to the allocated memory. The memory must be freed by calling LocalFree.
FORMAT_MESSAGE_FROM_STRING
flag is specified in dwFlags
.
If the function succeeds, the return value is the number of characters stored into the buffer pointed to by lpBuffer
, not including the terminating null character.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
The FormatMessage
function supports the following flags:
Flag | Description |
---|---|
FORMAT_MESSAGE_ALLOCATE_BUFFER |
If this flag is used with FORMAT_MESSAGE_FROM_STRING , lpBuffer is an LPWSTR or LPSTR. The function allocates a buffer large enough to hold the message and sets lpBuffer to point to the allocated buffer. The system uses the LocalAlloc function to allocate memory. Use the LocalFree function to free the buffer. |
FORMAT_MESSAGE_FROM_STRING |
The lpSource parameter is a pointer to a null-terminated string. The message is extracted from this string. |
FORMAT_MESSAGE_FROM_SYSTEM |
The message are retrieved from the system message table. The message identifier is passed in the dwMessageId parameter. |
FORMAT_MESSAGE_FROM_HMODULE |
The message are retrieved from the module specified by the lpSource parameter. The module must have been opened with the LOAD_LIBRARY_AS_DATAFILE flag. |
The FormatMessage
function formats a message string by inserting the values of the specified arguments into the message string. The insertion points are indicated by percent signs (%).
The format specifiers are similar to those used by the printf
function:
%1!type!
: Inserts a string argument.%n!type!
: Inserts an integer argument.%%
: Inserts a single percent sign.#include <windows.h> #include <stdio.h> int main() { DWORD errorCode = GetLastError(); // Get a sample error code LPVOID lpMsgBuf; DWORD bufLen; bufLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); if (bufLen == 0) { printf("FormatMessage failed with error %lu\n", GetLastError()); return 1; } printf("Error Code: %lu\n", errorCode); printf("Error Message: %s\n", (LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); // Free the buffer allocated by FormatMessage return 0; }