Step 1: Setting the Color Key

In addition to the other functions found in the doInit function of some of the other DirectDraw samples, the DDEX4 sample contains the code to set the color key for the sprites. Color keys are used for setting a color value that will be used for transparency. When the system contains a hardware blitter, all the pixels of a rectangle are blitted except the value that was set as the color key, thereby creating nonrectangular sprites on a surface. The code for setting the color key in DDEX4 is shown below:

// Set the color key for this bitmap (black).

DDSetColorKey(lpDDSOne, RGB(0,0,0));

return TRUE;

You can select the color key by setting the RGB values for the color you want in the call to the DDSetColorKey function. The RGB value for black is (0, 0, 0). The DDSetColorKey function calls the DDColorMatch function. (Both functions are in Ddutil.cpp.) The DDColorMatch function stores the current color value of the pixel at location (0, 0) on the bitmap located in the lpDDSOne surface. Then it takes the RGB values you supplied and sets the pixel at location (0, 0) to that color. Finally, it masks the value of the color with the number of bits per pixel that are available. After that is done, the original color is put back in location (0, 0), and the call returns to DDSetColorKey with the actual color key value. After it is returned, the color key value is placed in the dwColorSpaceLowValue member of the DDCOLORKEY structure. It is also copied to the dwColorSpaceHighValue member. The call to IDirectDrawSurface::SetColorKey then sets the color key.

You may have noticed the reference to CLR_INVALID in DDSetColorKey and DDColorMatch. If you pass CLR_INVALID as the color key in the DDSetColorKey call in DDEX4, the pixel in the upper-left corner (0, 0) of the bitmap will be used as the color key. As the DDEX4 bitmap is delivered, that does not mean much because the color of the pixel at (0, 0) is a shade of gray. If, however, you would like to see how to use the pixel at (0, 0) as the color key for the DDEX4 sample, open the All.bmp bitmap file in a drawing application and then change the single pixel at (0, 0) to black. Be sure to save the change (it's hard to see). Then change the DDEX4 line that calls DDSetColorKey to the following:

DDSetColorKey(lpDDSOne, CLR_INVALID);

Recompile the DDEX4 sample, and ensure that the resource definition file is also recompiled so that the new bitmap is included. (To do this, you can simply add and then delete a space in the Ddex4.rc file.) The DDEX4 sample will then use the pixel at (0, 0), which is now set to black, as the color key.