Convert HRESULT hex error code to string
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Convert HRESULT hex error code to string

  1. #1
    Join Date
    Mar 2010
    Posts
    42

    Convert HRESULT hex error code to string

    Hi all,



    Is there a way to convert an HRESULT hex error code to a string? To better illustrate this, here is a sample code:



    HRESULT hr = CoInitialize(NULL);

    if(FAILED(hr))
    {
    //This is what I want to store into a string.
    //"Failed to Initialize COM. Error code = 0x" << hex << hr << endl;

    string hexerrorcode = ?;

    CoUninitialize();
    return 0;
    }

    I am not sure how to put it into string.



    Can anyone help me with this?



    Thank you!

  2. #2
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Convert HRESULT hex error code to string

    Something like this (works for most windows error codes):

    Code:
    void ErrorMessage(DWORD dwError)
    {
        LPVOID pText = 0;
    
        ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 
    	      NULL,dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPWSTR)&pText,0,NULL);
        MessageBox(NULL,(LPCWSTR)pText,0,MB_OK);
        LocalFree(pText);
    }

  3. #3
    Join Date
    May 2002
    Posts
    1,435

    Re: Convert HRESULT hex error code to string

    Code:
    #include <string>
    #include <sstream>
    
    std::ostringstream oss;
    oss << "Failed to Initialize COM. Error code = 0x" << std::hex << hr << std::endl;
    std::string hexerrorcode = oss.str();

  4. #4
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Convert HRESULT hex error code to string

    Sorry, I misread the question.

  5. #5
    Join Date
    Mar 2003
    Location
    India {Mumbai};
    Posts
    3,871

    Re: Convert HRESULT hex error code to string

    With printf-family of functions you can simply use &#37;x or %X format specifier!
    My latest article: Explicating the new C++ standard (C++0x)

    Do rate the posts you find useful.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center