Codwiz51's Wiki

RSS

Navigation







Quick Search
»
Advanced Search »
I find Windows API error returns to be a little cryptic. GetLastError() does a nice job at supplying the API error number. But that is a little bit tough to decipher. This little code ditty will return an error message string for you to log or present to the user. (Resist that temptation: the error string may help you, but it will scare the poor user to death.)

The code also demonstrates how to obtain an error message from a module. In my case, I often need to interpret WinInet errors.

void GetErrorMessage( /* in */ DWORD dwErrIn, /* out */ CString * sMessage)
{
    LPTSTR lpMsgBuf;

    if (dwErrIn >= 12000 && dwErrIn <= 12174)
    
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_HMODULE,
            GetModuleHandle( _T("wininet.dll") ),
            dwErrIn,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0,
            NULL );
    }
    else
    {
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM,
            NULL,
            dwErrIn,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0,
            NULL );
    }

    *sMessage = lpMsgBuf;
    LocalFree(lpMsgBuf);
}

ScrewTurn Wiki version 3.0.2.509. Some of the icons created by FamFamFam.