2
votes

When creating a bitmap you have three four choices:

  • CreateBitmap: creates a device-dependent bitmap (and it better be compatible with the device you eventually intend to use it on)
  • CreateCompatibleBitmap: creates a device-dependent bitmap (compatible with the DC you supply)
  • CreateDIBitmap: creates a device-dependent bitmap, but lets you specify the device-independent bits to initialize the bitmap with1(functionally equivalent to calling CreateCompatibleBitmap + SetDIBits)
  • CreateDIBSection: creates a device-independant bitmap (but i have to supply a DC?)

It makes sense why CreateCompatibleBitmap would need an hdc parameter: it has to know which DC to be compatible with.

Note: It doesn't make sense why CreateBitmap doesn't take an hdc. How does it know what DC to be compatible with?

CreateBitmap doesn't take a DC, and it doesn't know what DC to be compatible with. That's your job. And you better make sure it's compatible with the DC you eventually intended to use it with.

Why does CreateDIBSection take a handle to a device context?

CreateDIBSection function

The CreateDIBSection function creates a DIB that applications can write to directly. The function gives you a pointer to the location of the bitmap bit values. You can supply a handle to a file-mapping object that the function will use to create the bitmap, or you can let the system allocate the memory for the bitmap.

| Function               | Type | Takes hdc |
|------------------------|------|-----------|
| CreateBitmap           | DDB  | No        |
| CreateCompatibleBitmap | DDB  | Yes       |
| CreateDIBitmap         | DDB  | Yes       |
| CreateDIBSection       | DIB  | Yes       |

What's the deal with DIBs?

Bonus Question

Q. What's the deal with CreateBitmap?

A. It's up to you to ensure it's compatible. Good luck! Or you can just use CreateCompatibleBitmap

Bonus Reading

1
@JonathanPotter And if iUsage is TBD?Ian Boyd
The HDC is necessary when using DIB_PAL_COLORS, as documented. Otherwise it's optional.Jonathan Potter
These functions date back to the stone age when video adapters could display only 16 or 256 colors and nobody could afford enough RAM to create a 24bpp bitmap. A 640x480x3 bitmap takes 900KB, you only had 640. Your current desktop wallpaper bitmap takes more space than the entire OS install back then. Palettes were not optional, so HDC wasn't. Time to move ahead already, GDI+ has been around for 20 years.Hans Passant
CreateDIBSection works if you pass NULL for the HDC, you can demonstrate this empirically simply by trying it. But it's not documented as such so I'm not really sure what you're looking for in an answer, unless someone from Microsoft with access to the source code wants to weigh in.Jonathan Potter

1 Answers

1
votes

The answer seems to be:

  • the hdc is only needed if usage = DIB_PAL_COLORS
  • otherwise (i.e. usage = DIB_RGB_COLORS) then hdc may be optional