OOPortal OOPortal


Basic COM   «Prev 

Using FormatMessage

Win32 API function FormatMessage can take in an HRESULT returned from a COM API call (for example, CoCreateInstance) or a COM interface method and return a string message that provides a short description of the error.

DWORD FormatMessage(  DWORD dwFlags,      
  LPCVOID lpSource,   
  DWORD dwMessageId,  
  DWORD dwLanguageId, 
  LPTSTR lpBuffer,    
  DWORD nSize,        
  va_list *Arguments);

The following code fragment demonstrates basic usage of FormatMessage:
#define EBUF_SIZ 2048

void ComErrorMsg(HRESULT hr) {
   TCHAR ebuf[EBUF_SIZ];

   FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
      NULL,
      hr,
      0,
      ebuf,
      EBUF_SIZ * sizeof(TCHAR),
      NULL);

   ::MessageBox(NULL, ebuf, ...);
}      

Function ComErrorMsg could be used as follows:
hr = CoCreateInstance(...);
if (FAILED(hr)) {
   ComErrorMsg(hr);
  ...
}

FormatMessage can also handle other (i.e., non-COM) Win32 API calls. Normally, you must call GetLastError to get the error code before calling FormatMessage. See the Microsoft Platform SDK documentation for more details.