See the question and my original answer on StackOverflow

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.