Voici la manière correcte d'obtenir un message d'erreur de la part du système pour une HRESULT
:
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 - log it, display it to the user, etc.
// release memory allocated by FormatMessage()
LocalFree(errorText);
errorText = NULL;
}
La principale différence entre cette réponse et celle de David Hanak est l'utilisation de l'option FORMAT_MESSAGE_IGNORE_INSERTS
drapeau. MSDN est un peu flou sur la façon dont les insertions doivent être utilisées, mais Raymond Chen note que vous ne devriez jamais les utiliser lors de la récupération d'un message système, car vous n'avez aucun moyen de savoir quelles insertions le système attend.
Pour info, si vous utilisez Visual C++, vous pouvez vous faciliter la vie en utilisant la fonction _com_error
classe :
{
_com_error error(hresult);
LPCTSTR errorText = error.ErrorMessage();
// do something with the error...
//automatic cleanup when error goes out of scope
}
Il ne fait pas partie du MFC ou de l'ATL directement, pour autant que je sache.