Search code examples
winapigdi

If a DibSection is independent of any device, why does it need a device context?


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


Solution

  • 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