有没有一种方法可以使用 win API 获得 HResult T 值的字符串表示形式?

在 winAPI 中是否有一个函数可以用来提取 HResult T 值的字符串表示?

问题是并非所有的返回值都记录在 MSDN 中,例如 ExecuteInDefaultAppDomain ()函数没有记录为返回“0x80070002-系统无法找到指定的文件。”但是,它确实存在!因此,我想知道是否有一个函数可以在通用情况下使用。

66683 次浏览

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

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.

Here's a sample using FormatMessage()

LPTSTR SRUTIL_WinErrorMsg(int nErrorCode, LPTSTR pStr, WORD wLength )
{
try
{
LPTSTR  szBuffer = pStr;
int nBufferSize = wLength;


//
// prime buffer with error code
//
wsprintf( szBuffer, _T("Error code %u"), nErrorCode);


//
// if we have a message, replace default with msg.
//
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL, nErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) szBuffer,
nBufferSize,
NULL );
}
catch(...)
{
}
return pStr;
} // End of SRUTIL_WinErrorMsg()

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

#include <system_error>


std::string message = std::system_category().message(hr)