Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the string representation of HRESULT value using win API?

Is there a function in win API which can be used to extract the string representation of HRESULT value?

The problem is that not all return values are documented in MSDN, for example ExecuteInDefaultAppDomain() function is not documented to return "0x80070002 - The system cannot find the file specified.", however, it does! Therefore, I was wondering whether there is a function to be used in common case.

like image 943
khkarens Avatar asked Aug 10 '11 08:08

khkarens


3 Answers

You can use _com_error:

_com_error err(hr);
LPCTSTR errMsg = err.ErrorMessage();

If you don't want to use _com_error for whatever reason, you can still take a look at its source, and see how it's done.

Don't forget to include the header comdef.h

like image 120
eran Avatar answered Oct 26 '22 17:10

eran


Since c++11, this functionality is built into the standard library:

#include <system_error>

std::string message = std::system_category().message(hr)
like image 36
Chronial Avatar answered Oct 26 '22 17:10

Chronial


The Windows API for this is FormatMessage. Here is a link that explains how to do it: Retrieving Error Messages.

For Win32 messages (messages with an HRESULT that begins with 0x8007, which is FACILITY_WIN32), you need to remove the hi order word. For example in the 0x80070002, you need to call FormatMessage with 0x0002.

However, it does not always work for any type of message. And for some specific messages (specific to a technology, a vendor, etc.), you need to load the corresponding resource DLL, which is not always an easy task, because you need to find this DLL.

like image 18
Simon Mourier Avatar answered Oct 26 '22 15:10

Simon Mourier