システムから返されるエラー メッセージを取得する適切な方法を次に示しますHRESULT
(この場合は hresult という名前です。または、に置き換えることができますGetLastError()
)。
LPTSTR errorText = NULL;
FormatMessage(
// use system message tables to retrieve error text
FORMAT_MESSAGE_FROM_SYSTEM
// allocate buffer on local heap for error text
|FORMAT_MESSAGE_ALLOCATE_BUFFER
// Important! will fail otherwise, since we're not
// (and CANNOT) pass insertion parameters
|FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM
hresult,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&errorText, // output
0, // minimum size for output buffer
NULL); // arguments - see note
if ( NULL != errorText )
{
// ... do something with the string `errorText` - log it, display it to the user, etc.
// release memory allocated by FormatMessage()
LocalFree(errorText);
errorText = NULL;
}
これと David Hanak の答えの主な違いは、FORMAT_MESSAGE_IGNORE_INSERTS
フラグの使用です。MSDN は、挿入をどのように使用する必要があるかについて少し不明確ですが、 Raymond Chen は、システム メッセージを取得するときに挿入を使用してはならないことを指摘しています。
_com_error
FWIW、Visual C++ を使用している場合は、次のクラスを使用して作業を少し楽にすることができます。
{
_com_error error(hresult);
LPCTSTR errorText = error.ErrorMessage();
// do something with the error...
//automatic cleanup when error goes out of scope
}
私の知る限り、MFC または ATL の一部ではありません。