How to convert an error code to an message ID? RRS feed

  • Question

  • How to convert the message ID returned by GetLastError() When calling GetLastError(), it returns an error code, but how to convert that code to a message ID? I have an error code, which Windows has for the message, but not the message ID, so it's only at non-compiled headers (ex: WinError.h) which has the code at the comments or at the declaration at the #define preprocessor constant variable name, which cannot be retrieved by compiled code because compiled code cannot interpret non-compiled ones, and this may make dependencies between the WinError.h file and the application (which may or may not be pre-compiled) and loops may decrease performance (windows error codes are 1000+) which is going to cause sluggish applications This is the code


    How to solve this and without loops?

    Some applications like Visual Studio are able to retrieve the message ID instantly

    I have tried a) searching winerror.h b) making own table (but no know-how to return the info from it) I have expected a) Success I have got a) nothing, only null string and it made the string terminate unexpectedly.

    Tuesday, March 7, 2023 1:59 PM

All replies

  • To convert the error code returned by GetLastError() to a message ID without using loops, you can use the FormatMessage function provided by the Windows API. This function can retrieve the message string for a given error code and format it according to your requirements.

    Here's an example of how to use the FormatMessage function to convert an error code to a message ID:

    • Declare a buffer to store the message string and initialize it to NULL:
    LPSTR messageBuffer = NULL;
    • Call the FormatMessage function, passing in the error code, the location of the buffer, the size of the buffer, and any additional formatting options you require:
    DWORD dwError = GetLastError();
                  FORMAT_MESSAGE_FROM_SYSTEM |

    Check if the function succeeded by checking the return value. If it succeeded, the message string will be stored in the buffer:

    if (messageBuffer != NULL)
        // Use the message string as needed
        printf("Error message: %s\n", messageBuffer);
        // Free the buffer
    By using the FormatMessage function, you can avoid the need for loops or custom tables to convert error codes to message IDs. Instead, the function will retrieve the message string for you and format it as required.


    Microsoft Docs. "FormatMessage function."

    • Proposed as answer by Hajira Banu Monday, March 27, 2023 5:59 PM
    Monday, March 27, 2023 5:58 PM
  • It returns "Access is denied" rather than "ERROR_ACCESS_DENIED" for the error code 5 (0x5).
    9 hours 25 minutes ago