2.3.2 Using a Color Palette

Before drawing to the display device with a color palette, an application must first create a logical palette by calling the CreatePalette function and then use the SelectPalette function to select the palette for the device context of the output device for which it will be used. An application cannot select a palette into a device context by using the SelectObject function.

All functions with a color parameter accept an index to an entry in the logical palette. The palette index specifier is a long integer value with the first bit in its high-order byte set to 1 and the palette index in the two low-order bytes. For example, 0x01000005 specifies the palette entry with an index of 5. The PALETTEINDEX macro accepts an integer value representing the index of a logical palette entry and returns a palette index value, which an application can use as a parameter for GDI functions that require a color.

An application can also specify a palette index indirectly by using a palette-relative RGB value. If the target display device supports logical palettes,
Win-dows matches the palette-relative RGB value to the closest palette entry.
If the target device does not support palettes, the RGB value is used as though it were an explicit RGB value. The palette-relative RGB value is identical to an explicit RGB value except that the second bit of the high-order byte is set to 1. For example, 0x02FF0000 specifies a palette-relative RGB value for pure blue. The PALETTERGB macro accepts values for red, green, and blue and returns a palette-relative RGB value, which an application can use as a parameter for GDI functions that require a color.

If an application specifies an RGB value instead of a palette entry, Windows uses the closest matching color in the default palette of 20 static colors.

If the source and destination device contexts have selected and realized different palettes, the BitBlt function does not properly move bitmap bits to or from a memory device context. In this case, you must call the GetDIBits function with the DIB_RGB_COLORS flag to retrieve the bitmap bits from the source bitmap in a device-independent format. Then you use the SetDIBits function to set the retrieved bits in the destination bitmap. This ensures that Windows properly matches colors between the two device contexts.

Note:

The BitBlt function successfully moves bitmap bits between two screen display contexts, even if they have selected and realized different palettes. The StretchBlt function properly moves bitmap bits between device contexts whether or not they use different palettes.