[C++] Win32: How to Show HRESULT Error message
void ShowError(LPCTSTR lpLibFileName, HRESULT hr, LPCTSTR lpFunctionName, LPCTSTR lpClassFunctionName)
{
setlocale(LC_ALL, "");
LPVOID a_pvMsgBuf;
TCHAR* a_pszMsg = NULL;
if(lpLibFileName == NULL)
{
if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
(DWORD)hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &a_pvMsgBuf, 0, NULL ))
{
a_pszMsg = (LPTSTR)a_pvMsgBuf;
// Do something with the error message.
_tprintf( TEXT("[ ERROR ] %s\n\tError Code: 0x%X\n\t%s <-- %s\n\n"), a_pszMsg, hr, lpFunctionName, lpClassFunctionName );
LocalFree(a_pvMsgBuf);
}
else
{
_tprintf( TEXT("[ ERROR ] Unknown Error: \n\t%s <-- %s\n\n"), lpFunctionName, lpClassFunctionName );
}
}
else
{
HMODULE hInst = LoadLibrary(lpLibFileName);
if(hInst)
{
if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS,
hInst,
(DWORD)hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &a_pvMsgBuf, 0, NULL ))
{
a_pszMsg = (LPTSTR)a_pvMsgBuf;
// Do something with the error message.
_tprintf( TEXT("[ ERROR ] %s\n\tError Code: 0x%X\n\t%s <-- %s\n\n"), a_pszMsg, hr, lpFunctionName, lpClassFunctionName );
LocalFree(a_pvMsgBuf);
}
else
{
ShowError(NULL, hr, lpFunctionName, lpClassFunctionName);
}
}
}
}