Without:
How can I use FormatMessage() to get the error text for a HRESULT?
HRES
As pointed out in other answers:
FormatMessage takes a DWORD result not a HRESULT (typically GetLastError()).LocalFree is needed to release memory that was allocated by FormatMessageI took the above points and added a few more for my answer:
FormatMessage in a class to allocate and release memory as neededoperator LPTSTR() const { return ...; } so that your class can be used as a stringclass CFormatMessage
{
public:
CFormatMessage(DWORD dwMessageId,
DWORD dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)) :
m_text(NULL)
{
Assign(dwMessageId, dwLanguageId);
}
~CFormatMessage()
{
Clear();
}
void Clear()
{
if (m_text)
{
LocalFree(m_text);
m_text = NULL;
}
}
void Assign(DWORD dwMessageId,
DWORD dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT))
{
Clear();
DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
FormatMessage(
dwFlags,
NULL,
dwMessageId,
dwLanguageId,
(LPTSTR) &m_text,
0,
NULL);
}
LPTSTR text() const { return m_text; }
operator LPTSTR() const { return text(); }
protected:
LPTSTR m_text;
};
Find a more complete version of the above code here: https://github.com/stephenquan/FormatMessage
With the above class, the usage is simply:
std::wcout << (LPTSTR) CFormatMessage(GetLastError()) << L"\n";