Handle to picture and back


The BitmapToPicture function is one of several Picture conversions I’ll be examining. Once you’ve seen it, IconToPicture, CursorToPicture, and Metafile­ToPicture will be easy. Here’s the code:

Function BitmapToPicture(ByVal hBmp As Long, _
Optional ByVal hPal As Long = hNull) _
As IPicture
‘ Fill picture description
Dim ipic As IPicture, picdes As PICTDESC, iidIPicture As IID
picdes.cbSizeofstruct = Len(picdes)
picdes.picType = vbPicTypeBitmap
picdes.hgdiobj = hBmp
picdes.hPalOrXYExt = hPal
‘ Fill in magic IPicture GUID {7BF80980-BF32-101A-8BBB-00AA00300CAB}
iidIPicture.Data1 = &H7BF80980
iidIPicture.Data2 = &HBF32
iidIPicture.Data3 = &H101A
iidIPicture.Data4(0) = &H8B
iidIPicture.Data4(1) = &HBB
iidIPicture.Data4(2) = &H0
iidIPicture.Data4(3) = &HAA
iidIPicture.Data4(4) = &H0
iidIPicture.Data4(5) = &H30
iidIPicture.Data4(6) = &HC
iidIPicture.Data4(7) = &HAB
‘ Create picture from bitmap handle
OleCreatePictureIndirect picdes, iidIPicture, True, ipic
‘ Result will be valid Picture or Nothing—either way set it
Set BitmapToPicture = ipic
End Function

First the function fills in the PICTDESC UDT. The Windows version of this structure contains unions so that one structure can contain different fields for bitmaps, icons, and metafiles. The last field of the structure is a Long hPal for bitmaps or two Integer fields (xExt and yExt) for metafiles (it’s ignored for icons). Unfortunately, Visual Basic doesn’t support writing unions, and it doesn’t recognize unions in type libraries. That’s OK. Unions are just a cheap trick for assigning different names to the same bits. I fake it by renaming the field hPalOrXYExt.


The next step is to fill a UDT with the magic numbers that uniquely identify the IPicture interface. Finally I call the OleCreatePictureIndirect API function. The last parameter is an IPicture interface which will be set by the function. I haven’t seen the source for OleCreatePictureIndirect, but I believe it creates a StdPicture object using the data passed in the picdes variable. It then passes back the IPicture interface of the new StdPicture object. As you might recall from Chapter 7, the StdPicture class implements several interfaces, including Picture and IPicture. There’s a lot more to the story. In fact, this code probably raises more questions than it answers, but I’ll leave the rest to lower level COM books.


So that takes care of the trip from bitmap to picture. The trip from picture to bitmap and palette is shorter and simpler. The StdPicture class and the Picture interface have a Handle property that returns the bitmap (or icon or metafile) handle of the GDI object in the picture. They also have an hPal property containing the palette handle of the bitmap. This property will always be 0 for icons and metafiles and for bitmaps that have no palette. The palette property is all you need to do palette tricks such as the one you’ll see in a few pages.