Technical Information Database TI2459C.txt Displaying an error string from GetLastError. Category :General Platform :All Product :Borland C++ All Description: Displaying an Error Message with GetLastError GetLastError is a WIN32 API that returns an error code indicating the most recent error. The most recent error will be set by the failing function. For example, if a call to LoadLibrary fails, LoadLibrary will call SetLastError. The error code returned by GetLastError can be found in WINERROR.H but another WIN32 API, FormatMessage, has built-in support for retrieving an appropriate error message string. FormatMessage is used to build up a message string given a number of options such as language. The source for the message can be a buffer or string resource found within a module. Additionally, FormatMessage supports a flag that will read the string from an operating system message table. The necessary flag is FORMAT_MESSAGE_FROM_SYSTEM. The following sample demonstrates using FormatMessage to allocate and fill a buffer with the most recent error ( returned by a call to GetLastError ). This example was built as a console mode application with the command line: bcc32 test.cpp Of course, in a WIN32 GUI application the buffer could be used in a call to MessageBox. #include #include int main() { LPVOID ptr = 0; // try a sure-to-fail API call such as one of the following LoadLibrary("sijvoaisjv"); // "library file...cannot be found" // LoadLibrary((char*)1234); // "The parameter is incorrect" FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), (LPTSTR)&ptr, 0, NULL); cout <<
Article originally contributed by Borland Staff