Detailed description of formatmessage usage

Source: Internet
Author: User
Tags print format

This article is translated from msdn

FormatmessageThe function is used to format a message string. The function requires a message definition as the input. This message definition can pass in this function through a buffer or a loaded message resource table module. The caller can also input the message definition by searching the system message resource table.FormatmessageIn a message resource table, a function uses a message identifier and a language identifier to find a message definition. If a function is called, the formatted message text is copied to an output buffer to process any embedded insertion sequence (Processing
Any embedded insert sequences if requested ).

Function prototype:

DWORD formatmessage (DWORDDwflags,// Resource processing method option-inLpcvoidLpsource,// Message resource-inDWORDDwmessageid,// Message Identifier-inDWORDDwageid,// Language Identifier-inLptstrLpbuffer,// Message buffer-outDWORDNsize,// Maximum message buffer value-inVa_list *Arguments// The inserted message array-in);

 

Parameter meaning:

Input option dwflags: indicates the message formatting process and how to translate the lpsource parameter. The lower byte of dwflags is responsible for how the function processes line breaks in the output buffer, and can also specify the maximum width of a formatted output row. Dwflags has a total of six parameters to choose from. One or more of them can be used in combination:

Format_message_allocate_buffer: Specify lpbuffer as an lpvoid pointer, and nsize as the minimum width (thchars) of the output message buffer. Allocate a buffer that is large enough for formatted messages and point lpbuffer to the address of the allocated buffer. After the allocated buffer is used up, the caller needs to use the localfree function to release the buffer pointed to by the lpbuffer to avoid Memory leakage.

Format_message_from_inserts: The insertion sequence in the message definition will be ignored, and the buffer zone will output the message, the message itself will not be changed (insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged), which is very useful for obtaining the message and then formatting it. If this flag is enabled, the arguments array is ignored.

Format_message_from_string: Point lpsource to a message definition ending with a null character. This message definition may contain the insertion sequence, just as a message text in a message resource table. It cannot be used with format_message_from_hmodule or format_message_from_system

Format_message_from_hmodule: lpsource indicates a module handle for searching message table resources. If lpsource is set to null, the current process of the current application image file will be searched. It cannot be used with format_message_from_string.

Format_message_from_system: searches the system message resource table for the response message. When format_message_from_system and fromat_message_from_hmodule are used together, the function first lpsource specifies a specific message resource table to search for the response message. If no response is found, the system message resource table is searched. It cannot be used with fromat_message_from_string. If format_message_from_system is enabled, the application can retrieve the system-defined error message text based on the return value of the getlasterror function.

Format_message_from_array: indicates that the arguments parameter is not a va_list structure, but a pointer to the value of the parameter array.

The maximum width of formatted output rows can be specified in the lower byte of dwflags. You can use the format_message_max_width_mask constant and the bitwise logic operation to set and obtain this maximum width value.

The following describes how formatmessage interprets its low byte value:

If the value is 0, the output row has no Width limit. The function stores the line breaks in the message definition text to the output buffer.

If it is a non-zero value and this value is not format_message_max_width_mask, it indicates that this non-zero value is the maximum number of bytes of an output row. The function ignores the line feed identifier in the message definition text. The function does not disconnect a character with a separator when changing the line. The function writes the hardcoded line feed in the message definition text to the output buffer. The hardcoded line feed is % N, which is the escape line break symbol.

If the value is format_message_max_width_mask, the function ignores the line feed identifier in the message definition text and outputs the line feed in the message definition text to the output buffer without generating new line breaks.

 

Input: lpsource, pointing to the location defined by the message. The type of this parameter depends on the setting of the dwflags parameter.

If dwflags is set to format_message_from_hmodule, lpsource is the handle to a module containing the message table that can be searched.

If dwflags is set to format_message_from_string, lpsource is a pointer to the unformatted message text. Scan Based on the inserted sequence and formatted Information.

If the dwflags setting is not one of the two above, or does not contain any of the two above, lpsource will be ignored.

 

Input: dwmessageid, indicating the message identifier of the request message. If the parameter items of dwflags contain format_message_from_string, dwmessageld is ignored, that is, it is invalid.

 

Input: dwlanuageid, indicating the language identifier of the request message. If the parameter items of dwflags contain format_message_from_string, dwlanuageid is ignored, that is, it is invalid.

If you input a langid, formatmessage only returns the message of the langid. If no message matches langid, error_resource_lang_not_found is returned. If dwlanuageid is set to 0, formatmessage searches for langids messages in the following sequence.

1. language neutral (language neutral)

2. Thread langid (thread langid), based on the local value of the thread

3. User defaultLangid, Based on the user's default locale Value

4. System DefaultLangid, Based on the system default locale Value

5. US English

If no message corresponding to the above langids is found in formatmessage, No matter what language the message text is, the message text is returned as is. If the execution fails, error_resource_lang_not_found is returned.

 

Output item: lpbuffer: pointer to a buffer for formatting messages (ended with null. If the dwflags parameter always includes format_message_allocate_buffer, the function calls the localalloc function to allocate a buffer for it, and the lpbuffer Pointer Points to the allocated buffer address.

Input: nsize. If the format_message_allocate_buffer flag is not set, the nsize parameter specifies the maximum number of characters that can be stored in the output buffer. If format_message_allocate_buffer is set, this nsize parameter specifies the minimum number of wide characters that can be stored in the output buffer. For ANSI text, nsize is the number of bytes, and for Unicode, it is the number of characters.

Input parameter: arguments, which indicates a pointer to a group of values used as the inserted value in the formatted message. In the formatted string, a % 1 indicates the first value in the parameter array, and a % 2 indicates the second parameter.

The interpretation of each value is related to the formatting information in the message definition. By default, it is a string pointer pointing to a null end.

By default, the arguments parameter is of the va_list * type and is a language used to describe the value of the Parameter Variable-and a specific data type for implementation. If the va_list * pointer type is not available, set it to the format_message_argument_array identifier and pass in a pointer to the array value. These are the inserted values in the formatted message. Each inserted value must have a corresponding variable in the array list.

 

Function return value:

If the execution is successful, return the value of the number of tchars that can store the wide character in the output buffer, including the null character. In fact, lpbuffer is returned, that is, the size of the requested buffer.

If the function fails to be executed, 0 is returned.

 

The formatmessage function can obtain the error message text based on the System-defined error code returned by getlasterror. For example:

LPVOID lpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM |FORMATE_MESSAGE_IGNORE_INSERTS,NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), //Default language(LPTSTR) &lpMsgBuf,0,NULL);//Process any inserts in lpMsgBuf.//......//Display the string MessageBox(NULL,(LPCTSTR)lpMsgBuf,"Error",MB_OK|MB_ICONINFORMATION);// Free the buffer.LocalFree(lpMsgBuf);

In message text, several escape characters support dynamic formatting of messages. The escape characters and their meanings are as follows:

% 0 indicates that a message text line is terminated without a new line break. This escape character can create a long line or terminate a message text line without creating a new line break. It is very useful for the prompt message type.

% N! Printf format string! This Escape Character indicates an insert value. The value of N ranges from 1 to 99. The print format character must be followed by an exclamation mark, that is, printf format string! The default print format is! S!

 

In WINXP, it is sometimes necessary to display the corresponding error text information based on the System-defined error code returned by network-related functions. The following describes how to display the error text based on the returned error code.

Generally, the error text message corresponding to the error code returned by the system network can be found in a netmsg. dll. This netmsg. dll contains error text information from nerr_base (2100) to max_nerr (nerr_base + 899) in % SystemRoot % \ System32. netmsg. dll. The corresponding error code number is defined in the SDK lmerr. h file.

You can use the loadlibrary and LoadLibraryEx functions to load the netmsg. dll file. The formatmessage function maps it to the corresponding error information based on the error code number returned by the netmsg. dll file module handle. The Code is as follows:

#include <windows.h>#include <stdio.h>#include <lmerr.h>void DisplayErrorText(DWORD dwLastError);#define RTN_OK 0#define RTN_USAGE 1#define RTN_ERROR 13int  _cdec main( int argc, char *argv[]){if(2 != argc){fprintf(stderr,"Usage: %s <error number> \n",argv[0]);return RTN_USAGE;}DisplayErrorText(atoi(argv[1]));return RTN_OK;}void DisplayErrorText(DWORD dwLastError){HMODULE hModule = NULL; //default to system sourceLPSTR MessageBuffer;DWORD dwBufferLength;DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_IGNORE_INSERTS |FORMAT_MESSAGE_FROM_SYSTEM;//// If dwLastError is in the network range, // load the message source.//if (dwLastError >= NERR_BASE && dwLastError <= MAX_NERR){hModule = LoadLibraryEx(TEXT("netmsg.dll"),NULL,LOAD_LIBRARY_AS_DATAFILE);if(hModule !=NULL)dwFormatFlags != FORMAT_MESSAGE_FROM_HMODULE;}//// Call FormatMessage() to allow for message// text to be acquired from the system// or from the supplied module handle.//if(dwBufferLength = FormatMessageA(dwFormatFlags,hModule, // module to get message from (NULL == system)dwLastError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // default language(LPSTR) &MessageBuffer,0,NULL)){DWORD dwBytesWritten;//// Output message string on stderr.//WriteFile(GetStdHandle(STD_ERROR_HANDLE),MessageBuffer,dwBufferLength,&dwBytesWritten,NULL);//// Free the buffer allocated by the system//LocalFree(MessageBuffer);}// // If we loaded a message source , unload it.//if(hModule != NULL)FreeLibrary(hModule);}

For example, if you input an error code number, it will display the corresponding error information based on the error code number.

C:\> netmsg 2453Could not find domain controller for this domain

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.