Home

FormatMessage

FormatMessage is a Windows API function that formats a message string by optionally loading the text from a system or module resource and performing inserts for arguments. It is available as FormatMessageA (ANSI), FormatMessageW (Unicode), and the generic FormatMessage macro maps to one of these depending on the build. The function is commonly used to obtain human-readable error messages corresponding to error codes from GetLastError, but it can also format messages defined in resources or supplied as strings.

The function supports several flags that control its behavior. FORMAT_MESSAGE_ALLOCATE_BUFFER tells the system to allocate the

Usage patterns are common in error handling and localization. A typical pattern is to retrieve a system

Return value is the number of TCHARs stored in the output buffer, excluding the terminating null. If

output
buffer;
FORMAT_MESSAGE_FROM_SYSTEM
searches
the
system
message-table
resources
for
the
requested
message;
FORMAT_MESSAGE_FROM_HMODULE
searches
a
specific
module’s
resources;
FORMAT_MESSAGE_FROM_STRING
treats
lpSource
as
the
message
string
itself.
FORMAT_MESSAGE_IGNORE_INSERTS
disables
insertion
processing,
while
FORMAT_MESSAGE_ARGUMENT_ARRAY
allows
you
to
supply
an
array
of
arguments
for
inserts
like
%1,
%2,
and
so
on.
When
FORMAT_MESSAGE_ARGUMENT_ARRAY
is
used,
the
last
parameter
points
to
an
array
of
pointers
to
the
insert
strings;
otherwise,
arguments
may
be
supplied
via
a
va_list.
error
string
with
FORMAT_MESSAGE_ALLOCATE_BUFFER
|
FORMAT_MESSAGE_FROM_SYSTEM,
passing
NULL
for
lpSource
and
a
zero
language,
then
freeing
the
allocated
buffer
with
LocalFree.
Another
pattern
uses
FORMAT_MESSAGE_FROM_HMODULE
to
load
strings
from
a
specific
DLL’s
resources,
supplying
a
module
handle.
If
a
string
template
includes
inserts,
provide
the
arguments
accordingly
or
use
FORMAT_MESSAGE_FROM_STRING
with
FORMAT_MESSAGE_ALLOCATE_BUFFER.
the
function
fails,
it
returns
zero
and
extended
error
information
can
be
retrieved
with
GetLastError.