RAD Studio 10.4.1 is now available! Learn more. Looking for discounts? Visit our Special Offers page!
C++

Displaying an error string from GetLastError.

Author: Embarcadero USA

 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


Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Learn More About Upgrading

Related posts
C++News

Using C++17 Algorithms Library Parallel Sorting with C++Builder 10.4 Sydney for Win32 and Win64

C++News

C++Builder and Platforms Support

C++

What's New in the GetIt Package Manager - June 2020

C++

RAD Studio 10.4 Now Available, Learn More

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES