Link to home
Start Free TrialLog in
Avatar of JiriNovotny
JiriNovotny

asked on

HICON icon handle - save icon to HDD

Hello,

I have a HICON icon handle, and I'd like to save it to HDD as an .ico file.
I haven't found any icon-saving function, nor HBITMAP-saving function.

I'm using Visual C++ 6.0 (SP6) MFC Dialog application.

Thanks.
Avatar of jkr
jkr
Flag of Germany image

See the article at http://www.codeguru.com/cpp/g-m/bitmap/article.php/c1697/ ("Writing a bitmap to a BMP file"). the scoop is to

// WriteDIB            - Writes a DIB to file
// Returns            - TRUE on success
// szFile            - Name of file to write to
// hDIB                  - Handle of the DIB
BOOL WriteDIB( LPTSTR szFile, HANDLE hDIB)
{
      BITMAPFILEHEADER      hdr;
      LPBITMAPINFOHEADER      lpbi;

      if (!hDIB)
            return FALSE;

      CFile file;
      if( !file.Open( szFile, CFile::modeWrite|CFile::modeCreate) )
            return FALSE;

      lpbi = (LPBITMAPINFOHEADER)hDIB;

      int nColors = 1 << lpbi->biBitCount;

      // Fill in the fields of the file header
      hdr.bfType            = ((WORD) ('M' << 8) | 'B');      // is always "BM"
      hdr.bfSize            = GlobalSize (hDIB) + sizeof( hdr );
      hdr.bfReserved1       = 0;
      hdr.bfReserved2       = 0;
      hdr.bfOffBits            = (DWORD) (sizeof( hdr ) + lpbi->biSize +
                                    nColors * sizeof(RGBQUAD));

      // Write the file header
      file.Write( &hdr, sizeof(hdr) );

      // Write the DIB header and the bits
      file.Write( lpbi, GlobalSize(hDIB) );

      return TRUE;
}

Since icons and bitmaps use the same format, that works for icons too.
BTW, see also http://msdn2.microsoft.com/en-us/library/ms997538.aspx ("Icons in Win32"). The sample code attached to the article (http://download.microsoft.com/download/win95/utility/1.0/w9xxp/en-us/4493.exe) should prove quite useful.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial