Palettes
Have you ever written a Windows application that makes generous use of color only to find that the output looks crummy on 16-color and 256-color video adapters? There's not a whole lot you can do about it when the adapter itself supports only 16 colors , but you can do plenty to improve output on 256-color devices. The key to better color output is MFC's CPalette class. Before we get into the specifics of CPalette, let's briefly review how color information is encoded in Windows and what Windows does with The Color Information That You Provide.
How Windows Uses Color
One of the benefits of a device-independent output model is that you can specify the colors an application uses without regard for the physical characteristics of the output device. When you pass a color to the Windows GDI, you pass a COLORREF value containing 8 bits Each for Red, Green, And Blue. The RGB Macro Combines Individual Red, Green, and Blue Values Into a Single Colorref. The Statement
ColorRef CLR = RGB (255, 0, 255);
creates a COLORREF value named clr that represents magenta-the color you get when you mix equal parts red and blue. Conversely, you can extract 8-bit red, green, and blue values from a COLORREF value with the GetRValue, GetGValue, and GetBValue Macros. a Number of GDI Functions, Including Those That Create Pens and Brushes, Accept ColorRef Values.
What the GDI does with the COLORREF values you pass it depends on several factors, including the color resolution of the video hardware and the context in which the colors are used. In the simplest and most desirable scenario, the video adapter is a 24-bits -per-pixel device and COLORREF values translate directly into colors on the screen. Video adapters that support 24-bit color, or true color, are becoming increasingly common, but Windows still runs on millions of PCs whose video adapters are limited to 4 or 8 bits per pixel. Typically, these devices are palletized devices, meaning that they support a wide range of colors but can display only a limited number of colors at one time. A standard VGA, for example, can display 262,144 different colors-6 bits each for red, green, and blue. However, a VGA running at a resolution of 640 by 480 pixels can display only 16 different colors at once because each pixel is limited to 4 bits of color information in the video buffer. The more common c ase is a video adapter that can display more than 16.7 million colors but can display only 256 colors at once. The 256 colors that can be displayed are determined from RGB values that are programmed into the adapter's hardware palette.Windows handles palletized devices by preprogramming a standard selection of colors into the adapter's hardware palette. A 256-color adapter is preprogrammed with the 20 so-called static colors shown in the following table. The four colors marked with asterisks are subject to change at the operating system's behest, so you shouldn 'T Write Code That Depends on Their Presence.
Static Palette Colors
ColorRGBColorRGBBlack000Cream * 255251240Dark red12800Intermediate gray * 160160164Dark green01280Medium gray128128128Dark yellow1281280Red25500Dark blue00128Green02550Dark magenta1280128Yellow2552550Dark cyan0128128Blue00255Light gray192192192Magenta2550255Money green * 192220192Cyan0255255Sky blue * 166202240White255255255 * Denotes default colors that are subject to change.
When you draw on a palletized device, the GDI maps each COLORREF value to the nearest static color using a simple color-matching algorithm. If you pass a COLORREF value to a function that creates a pen, Windows assigns the pen the nearest static color. If you pass a COLOREF value to a function that creates a brush and there is not a matching static color, Windows dithers the brush color using static colors. Because the static colors include a diverse (if limited) assortment of hues, Windows can do a reasonable job of simulating any COLORREF value you throw at it. A picture painted with 100 different shades of red will not come out very well because Windows will simulate all 100 shades with just two reds. But you're guaranteed that red won ' T Undergo A Wholesale Transformation To Blue, Green, OR Some Other Color, Because The Static Colors Are Always There and is ALWAYS AVAILABLE.
For many applications, the primitive form of color mapping that Windows performs using static colors is good enough. But for others, accurate color output is a foremost concern and 20 colors just will not get the job done. In a single-tasking environment such as MS-DOS, a program running on a 256-color adapter can program the hardware palette itself and use any 256 colors it wants. In Windows, applications can not be allowed to program the hardware palette directly because the video adapter is a shared resource. So how do you take advantage of the 236 colors left unused in a 256-color adapter after Windows adds the 20 static colors? The answer lies in a GDI object known as a logical palette.Logical Palettes and the CPalette Class
A logical palette is a table of RGB color values that tells Windows what colors an application would like to display. A related term, system palette, refers to the adapter's hardware color palette. At an application's request, the palette manager built into Windows will transfer the colors in a logical palette to unused entries in the system palette-a process known as realizing a palette-so that the application can take full advantage of the video adapter's color capabilities. With the help of a logical palette, an application running on a 256-color video adapter can use the 20 static colors plus an additional 236 colors of its choosing. and because all requests to realize a palette go through the GDI, the palette manager can serve as an arbitrator between programs with conflicting color needs and thus ensure That the system palette is buy cooperative.
What happens if two or more applications realize logical palettes and the sum total of the colors they request is more than the 236 additional colors a 256-color video adapter can handle? The palette manager assigns color priorities based on each window's position in the z- order. The window at the top of the z-order receives top priority, the window that's second gets the next highest priority, and so on. If the foreground window realizes a palette of 200 colors, all 200 get mapped to the system palette. If a background window then realizes a palette of, say, 100 colors, 36 get programmed into the unused slots remaining in the system palette and 64 get mapped to the nearest matching colors. That's the worst case. Unless directed to do otherwise, the palette manager avoids duplicating entries in the system palette. Therefore, if 4 of the foreground window's colors and 10 of the background window's colors match static colors, and if another 10 of the background window's colors match nons That.
You can see the palette manager at work by switching Windows to 256-color mode, launching two instances of the Windows Paint applet, loading a different 256-color bitmap in each, and clicking back and forth between the two. The bitmap in the foreground will always look the best because it gets first crack at the system palette. The bitmap in the background gets what's left over. If both bitmaps use similar colors, the background image will not look too bad. But if the colors are vastly different- for example, if bitmap A contains lots of bright, vibrant colors whereas bitmap B uses primarily earth tones-the image in the background window might be so color-corrupted that it's hardly recognizable. The palette manager's role in the process is to try to satisfy THEEN th fews
Writing an application that uses a logical palette is not difficult. In MFC, logical palettes are represented by the CPalette class and are created and initialized with CPalette member functions. Once a logical palette is created, it can be selected into a device context and Realized with cdc member functions.
. CPalette provides two member functions for palette creation CreatePalette creates a custom palette from RGB values you specify; CreateHalftonePalette creates a "halftone" palette containing a generic and fairly uniform distribution of colors Custom palettes give better results when an image contains few distinctly different colors. BUT MANY SUBTLE VARIATIONS IN TONE. HALFTONE PALETTES WORK Well for Images Containing A Wide Range of Colors. The StatementsCpalette Palette;
Palette.createhalftonePalette (PDC);
create a halftone palette tailored to the device context pointed to by pDC If the device context corresponds to a 256-color device, the halftone palette will also contain 256 colors Twenty of the colors will match the static colors;.. the other 236 will expand the selection of colors available by adding subtler shades of red, green, and blue and mixtures of these primary colors. Specifically, a 256-color halftone palette includes all the colors in a 6-by-6-by-6-color cube ( colors composed of six shades each of red, green, and blue), plus an array of grays for gray-scale imaging and other colors handpicked by the GDI. Passing a NULL DC handle to CreateHalftonePalette creates a 256-color halftone palette independent of the . characteristics of the output device However, because CPalette :: CreateHalftonePalette mistakenly asserts in debug builds if passed a NULL DC handle, you must drop down to the Windows API to take advantage of this feature:
CPALETTE PALETTE;
Palette.attach (:: CREATEHALFTONEPALETTE (NULL);
:: CREATEHALFTONEPALETTE IS The API Equivalent of CPALETTE :: CREATEHALFTONEPALETTE.
Creating a custom palette is a little more work because before you call CreatePalette, you must initialize a LOGPALETTE structure with entries describing the palette's colors. LOGPALETTE is defined as follows.typedef struct tagLOGPALETTE {
Word Palversion;
Word Palnumentries;
Paletteentry Palpalent [1];
Logpalette;
palVersion specifies the LOGPALETTE version number; in all current releases of Windows, it should be set to 0x300 palNumEntries specifies the number of colors in the palette palPalEntry is an array of PALETTEENTRY structures defining the colors The number of elements in the array should... Equal the value of palamntries. Paletteentry is defined Like this:
Typedef struct tagpaletteentry {
BYTE PERED;
Byte pegreen;
Byte peblue;
Byte peflags;
} Paletteentry;
peRed, peGreen, and peBlue specify a color's 8-bit RGB components. peFlags contains zero or more bit flags describing the type of palette entry. It can be set to any of the values shown here, or to 0 to create a "normal" Palette Entry:
FlagDescriptionPC_EXPLICITCreates a palette entry that specifies an index into the system palette rather than an RGB color. Used by programs that display the contents of the system palette.PC_NOCOLLAPSECreates a palette entry that's mapped to an unused entry in the system palette even if there's already an entry for that color. Used to ensure the uniqueness of palette colors.PC_RESERVEDCreates a palette entry that's private to this application. When a PC_RESERVED entry is added to the system palette, it is not mapped to colors in other logical palettes even if the colors match . Used by Programs That Perform Palette Animation.
Most of the time, peFlags is simply set to 0. We'll discuss one use for the PC_RESERVED flag later in this chapter, in the section on palette animation.The PALETTEENTRY array in the LOGPALETTE structure is declared with just one array element because Windows . has no way of anticipating how many colors a logical palette will contain As a result, you can not just declare an instance of LOGPALETTE on the stack and fill it in; instead, you have to allocate memory for it based on the number of Paletteentry Structures It Contains. The Following Code Allocates A "Full" Logpalette Structure on The Stack and the Creates A Logical Palette Containing 32 Shades of Red:
Struct {
Logpalette lp;
Paletteentry APE [31];
} PAL;
Logpalette * PLP = (logpalette *) & Pal;
PLP-> paversion = 0x300;
PLP-> PALNUMENTRIES = 32;
For (int i = 0; i <32; i ) {
PLP-> palpalentry [i] .pled = i * 8;
PLP-> Palpalentry [i] .pegreen = 0;
PLP-> PALPALENTRY [I] .peblue = 0;
PLP-> Palpalent [I] .peflags = 0;
}
CPALETTE PALETTE;
Palette.createPalette (PLP);
Like other GDI objects, logical palettes should be deleted when they're no longer needed. A logical palette represented by a CPalette object is automatically deleted when the corresponding CPalette object is deleted or goes out of scope.
How many entries can a logical palette contain? As many as you want it to. Of course, the number of colors that can be mapped directly to the system palette is limited by the capabilities of the video adapter. If you realize a palette containing 1,024 colors on a 256-color output device, only the first 236 will be mapped directly;. the remaining colors will be matched as closely as possible to colors already in the system palette When you use logical palettes (especially large ones), it's helpful to arrange the colors in order of importance, where palPalEntry [0] defines the most important color, palPalEntry [1] defines the next most important color, and so on. The palette manager maps palette colors in array order, so by putting important colors first , you increase the chances that those colors will be displayed in their native form. in general, you should not make a logical palette any larger than it has to be. Large palettes take longer to realize, and the more palette colors a foregro und window uses, the fewer colors the palette manager can make available to palette-aware windows lower in the z-order.After a palette is created, you can retrieve individual palette entries with CPalette :: GetPaletteEntries or change them with CPalette :: SetPaletteEntries . You can also resize A Palette with cpalette :: ResizePalette. If the parain entries INITIALLY Contain All 0s.
Realizing a logical palette
For a logical palette to be effective, it must be selected into a device context and realized before any drawing takes place. The current logical palette is a device context attribute, just as the current pen and brush are device context attributes. (In case you 're wondering, a device context's default logical palette is a trivial one whose entries correspond to the static colors) The following OnPaint handler selects the logical palette m_palette into a paint device context and realizes the palette before repainting the screen:. void CMainWindow :: OnPaint ()
{
CPAINTDC DC (this);
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette, False);
Dc.RealizePalette ();
// do some dusting.
Dc.selectPalette (Poldpalette, False);
}
In this example, the pointer to the default palette is saved and used later to select m_palette out of the device context. Note that palettes are selected with CDC :: SelectPalette instead of CDC :: SelectObject. The second parameter is a BOOL value that, if TRUE, forces the palette to behave as if it were in the background even when the window that selected it is in the foreground. background palettes can be handy in applications that use multiple palettes, but normally you'll specify FALSE in calls to SelectPalette . CDC: RealizePalette Realizes The Palette That's Currently Selected Into The Device Context by asking The Palette Manager to map colors from the logical palette to the system palette.
Drawing with Palette Colors
Once you create a palette, select it into a device context, and realize it, you're ready to start drawing. If you use CDC :: BitBlt to display a bitmap, the realized colors are used automatically. But if you're drawing images with brushes or pens or using functions such as CDC :: FloodFill that use neither a brush nor a pen directly but do accept COLORREF values, there's something else you must consider.The RGB macro is one of three macros that create COLORREF values. The others are PALETTEINDEX and PALETTERGB. Which of the three macros you use determines how the GDI treats the resultant COLORREF. When you draw with a COLORREF value created with the RGB macro, the GDI ignores the colors that were added to the system palette when the logical palette was realized and uses only the static colors. If you want the GDI to use all the palette colors, use the PALETTERGB macro. PALETTERGB creates a palette-relative color. The PALETTEINDEX macro creates a COLORREF value that specifies an index into a logical palette rather than an RGB color value. This value is called a palette-index color value. It's the fastest kind of color to draw with because it prevents the GDI from having to match RGB color values to colors in the logical palette.
The Following Code Sample Demonstrates How All Three Macros Are Used:
Void cmainwindow :: onpaint ()
{
CPAINTDC DC (this);
// select and realize a logical pastete.
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette, False);
Dc.RealizePalette ();
// CREATE Three Pens.
CPEN PEN1 (PS_SOLID, 16, RGB (242, 36, 204);
CPEN PEN2 (PS_SOLID, 16, Palettergb (242, 36, 204);
CPEN PEN3 (PS_SOLID, 16, PALETTEINDEX (3));
// do some dusting.
Dc.moveto (0, 0);
CPEN * POLDPEN = DC.SelectObject (& Pen1); DC.LineTo (300, 0); // Nearest Static Color
Dc.selectObject (& Pen2);
Dc.LineTo (150, 200); // Nearest Static or Palette Color
Dc.selectObject (& Pen3);
Dc.LineTo (0, 0); // Exact Palette Color
Dc.selectObject (Poldpen);
// Select the Palette Out of the device context.
Dc.selectPalette (Poldpalette, False);
}
Because pens use solid, undithered colors and because its COLORREF value is specified with an RGB macro, pen1 draws with the static color that most closely approximates the RGB value (242, 36, 204). Pen2, on the other hand, is assigned the NEAREST MATCHING Color from The Static Colors Or M_Palette. Pen3 Uses The Color in The System Palette That Corresponds To The Fourth Color (INDEX = 3) In The Logical Palette, Regardless of What That Color Might BE.
The WM_QuerynewPalette and WM_Palettechanged Messages
When you write an application that uses a logical palette, you should include handlers for a pair of messages named WM_QUERYNEWPALETTE and WM_PALETTECHANGED. WM_QUERYNEWPALETTE is sent to a top-level window when it or one of its children receives the input focus. WM_PALETTECHANGED is sent to all top-level windows in the system when a palette realization results in a change to the system palette. An application's normal response to either message is to realize its palette and repaint itself. Realizing a palette and repainting in response to a WM_QUERYNEWPALETTE message enables a window that was just brought to the foreground to put on its best face by taking advantage of the fact that it now has top priority in realizing its palette. Realizing a palette and repainting in response to a WM_PALETTECHANGED message enable background windows to adapt to changes in THE SYSTEM PALETTE AND Take Advantage Of Any Unused Entries That Remain After Windows Higher In The Z-Order Have Realized Their PA Lettes.The Following Message Handler Demonstrates a Typical Response To A WM_QUERYNEWPALETTE Message:
// in The Message Map
ON_WM_QUERYNEWPALETTE ()
Bool cmainwindow :: ONQUERYNEWPALETTE ()
{
CClientDC DC (this);
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette, False);
Uint ncount;
IF (ncount = DC.RealizePalette ())
Invalidate ();
Dc.selectPalette (Poldpalette, False);
Return ncount;
}
The general strategy is to realize a palette and force a repaint by invalidating the window's client area. The value returned by RealizePalette is the number of palette entries that were mapped to entries in the system palette. A 0 return value means that realizing the palette had no effect, which should be extremely rare for a foreground window. If RealizePalette returns 0, you should skip the call to Invalidate. OnQueryNewPalette should return a nonzero value if a logical palette was realized and 0 if it was not. It should also return 0 if it tried to realize a palette but RealizePalette returned 0. The return value is not used in current versions of Windows.WM_PALETTECHANGED messages are handled in a similar way Here's what a typical OnPaletteChanged handler looks like.:
// in The Message Map
ON_WM_PALETTECHANGED ()
Void CMainWindow :: OnPalettechanged (CWND * PfocusWnd)
{
IF (pfocusWnd! = this) {
CClientDC DC (this);
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette,
FALSE);
IF (DC.RealizePalette ())
Invalidate ();
Dc.selectPalette (Poldpalette, False);
}
}
The CWnd pointer passed to OnPaletteChanged identifies the window that prompted the WM_PALETTECHANGED message by realizing a palette. To avoid unnecessary recursion and possible infinite loops, OnPaletteChanged should do nothing if pFocusWnd points to its own window. That's the reason for the if statement that compares pFocusWnd THIS.
Rather than perform full repaints in response to WM_PALETTECHANGED messages, applications can optionally call CDC :: UpdateColors instead. UpdateColors updates a window by matching the color of each pixel to the colors in the system palette. It's usually faster than a full repaint, but the results typically are not as good because the color matching is done based on the contents of the system palette before it changed. If you use UpdateColors, maintain a variable that counts the number of times UpdateColors has been called. Then every third or fourth time , do a full repaint and reset the counter to 0. This will prevent the colors in a background window from becoming too out of sync with the colors in the system palette.Handling Palette Messages in Document / View Applications
. The OnQueryNewPalette and OnPaletteChanged handlers in the previous section assume that the window to be updated is the application's main window In a document / view application, that's not the case; the views need updating, not the top-level window The ideal solution would. Be to Put The ONQUERYNEWPALETTE AND ONPALETTECHANGED HANDLERS IN The View Class, Buthat Work Because Views Don't Receive Palette Messages-Only Top-Level Windows Do.
What most document / view applications do instead is have their main windows update the views in response to palette messages The following OnQueryNewPalette and OnPaletteChanged handlers work well for most SDI applications.:
Bool CMAINFRAME :: ONQUERYNEWPALETTE ()
{
CDocument * pdoc = getActiveDocument ();
IF (PDOC! = NULL)
GetActiveDocument () -> UpdateAllViews (NULL);
Return True;
}
Void CMAINFRAME :: OnPalettechanged (CWND * PFOCUSWND)
{
IF (pfocusWnd! = this) {
CDocument * pdoc = getActiveDocument (); if (pdoc! = Null)
GetActiveDocument () -> UpdateAllViews (NULL);
}
}
Palettes are a little trickier in MDI applications. If each open document has a unique palette associated with it (as is often the case), the active view should be redrawn using a foreground palette and inactive views should be redrawn using background palettes. Another issue with MDI applications that use multiple palettes is the need to update the views' colors as the user clicks among views. The best solution is to override CView :: OnActivateView so that a view knows when it's activated or deactivated and can realize its palette accordingly. For a Good Example of Palette Handling In MDI Applications, See The Diblook Sample Program Provided with Visual C .
DETERMINININING WHETHER A Logical Palette Is Needed
Now that you understand the mechanics of palette usage, ask yourself this question:? How do I know if I need a logical palette in the first place If color accuracy is of paramount concern, you'll probably want to use a logical palette when your application runs on a palletized 256-color video adapter. But the same application does not need a logical palette when the hardware color depth is 24 bits because in that environment perfect color output comes for free. And if the application runs on a standard 16 -Color VGA, Palettes Area Extraneous Because The System Palette Contains 16 Static Colors That Leave No Room for Colors in Logical Palettes.
You can determine at run time whether a logical palette will improve color output by calling CDC :: GetDeviceCaps with a RASTERCAPS parameter and checking the RC_PALETTE bit in the return value, as demonstrated here:
CClientDC DC (this);
Bool busEpalette = false;
IF (DC.GETDEVICECAPS (RasterCaps) & rc_palette
Busepalette = true;
RC_PALETTE is set in palettized color modes and clear in nonpalettized modes. Generally speaking, the RC_PALETTE bit is set in 8-bit color modes and clear in 4-bit and 24-bit color modes. The RC_PALETTE bit is also clear if the adapter is running in 16-bit color ( "high color") mode, which for most applications produces color output every bit as good as true color. Do not make the mistake some programmers have made and rely on bit counts to tell you whether to use a palette. As sure as you do, you'll run across an oddball video adapter that defies the normal conventions and fools your application into using a palette when a palette is not needed or not using a palette when a palette would help.
What happens if you ignore the RC_PALETTE setting and use a logical palette regardless of color depth? The application will still work because the palette manager works even on nonpalettized devices. If RC_PALETTE is 0, palettes can still be created and selected into device contexts, but calls to RealizePalette do nothing. PALETTEINDEX values are dereferenced and converted into RGB colors in the logical palette, and PALETTERGB values are simply treated as if they were standard RGB color values. OnQueryNewPalette and OnPaletteChanged are not called because no WM_QUERYNEWPALETTE and WM_PALETTECHANGED messages are sent . As explained in an excellent article, "The Palette Manager: How and Why," available on the Microsoft Developer Network (MSDN), "The goal is to allow applications to use palettes in a device-independent fashion and to not worry about the Actual Palette Capabilities of The Device Driver. "STILL, You CAN Avoid Wasted CPU CYCLES BY Checking The RC_PALETTE FLAG AND SKIPPING PALET te-related function calls if the flag is clear. And if your application relies on the presence of hardware palette support and will not work without it-for example, if it uses palette animation, a subject we'll get to in a moment -You can use rc_palette to determine WHETHER Your Application Is Even Capable of Running On The Current Hardware.
An equally important question to ask yourself when considering whether to use logical palettes is, "How accurate does my program's color output need to be?" Applications that draw using colors that match the static colors do not need palettes at all. On the other hand, a bitmap file viewer almost certainly needs palette support because without it all but the simplest bitmaps would look terrible on 256-color video adapters. Assess your program's color needs, and do as little work as you have to. you'll write better Applications as a result.The Palettedemo Application
The application shown in Figure 15-1 demonstrates basic palette-handling technique in a non-document / view application. PaletteDemo uses a series of blue brushes to paint a background that fades smoothly from blue to black. Moreover, it produces a beautiful gradient fill even on 256-color video adapters. The key to the high quality of its output on 256-color screens is PaletteDemo's use of a logical palette containing 64 shades of blue, ranging from almost pure black (R = 0, G = 0, B = 3) to high-intensity blue (R = 0, G = 0, B = 255). Brush colors are specified using palette-relative COLORREF values so that the GDI will match the brush colors to colors in the system palette after the logical palette is realized. You can judge the results for yourself by running PaletteDemo in both 8-bit and 24-bit color modes and seeing that the output is identical. Only when it is run in 16-color mode does PaletteDemo fail to produce a smooth Gradient Fill. But Even the results aren't Bad Because The GDI DIT Hers the brush colors.
Figure 15-1. The Palettedemo window.
Here are a few points of interest in PaletteDemo's source code, which appears in Figure 15-2. For starters, PaletteDemo's main window paints the gradient-filled background in response to WM_ERASEBKGND messages. WM_ERASEBKGND messages are sent to erase a window's background before a WM_PAINT handler paints the foreground. A WM_ERASEBKGND handler that paints a custom window background as PaletteDemo does should return a nonzero value to notify Windows that the background has been "erased." (For a cool effect, see what happens when a WM_ERASEBKGND handler paints nothing but returns TRUE anyway. What do you get? A see-through window!) Otherwise, Windows erases the background itself by filling the window's client area with the WNDCLASS's background brush.PaletteDemo creates the logical palette that it uses to paint the window background in CMainWindow :: oncreate. The Palette Itself Is A CPalette Data MEMBER NAMED M_PALETTE. Before Creating The Palette, Oncreate Checks CDC :: getDevicecaps' . Turn value for an RC_PALETTE bit If the bit is not set, OnCreate leaves m_palette uninitialized Before selecting and realizing the palette, CMainWindow :: OnEraseBkgnd checks m_palette to determine whether a palette exists.:
IF (HPALETTE) m_palette! = null) {
Poldpalette = PDC-> SelectPalette (& M_Palette, False);
PDC-> RealizePalette ();
}
CPalette's HPALETTE operator returns the handle of the palette attached to a CPalette object. A NULL handle means m_palette is uninitialized. OnEraseBkgnd adapts itself to the environment it's run in by selecting and realizing a logical palette if and only if the video hardware is palettized. The DoGradientFill function that draws the window background works with or without a palette because brush colors are specified with PALETTERGB macros.One consideration that PaletteDemo does not address is what happens if the color depth changes while the application is running. You can account for such occurrences by processing WM_DISPLAYCHANGE messages, which are sent when the user changes the screen's resolution or color depth, and reinitializing the palette based on the new settings. There is no ON_WM_DISPLAYCHANGE macro, so you have to do the message mapping manually with ON_MESSAGE. The wParam parameter ENCAPSULATED IN A WM_DISPLAYCHANGE Message Contains The New Color Depth Expressed As The N Umber of bits per pixel, and the low and high Words of lparam contain the Latest Horizontal and Vertical Screen Resolution in Pixels.
WM_DISPLAYCHANGE is not only for applications that use palettes. You should also use it if, for example, you initialize variables with the average width and height of a character in the system font when the application starts and later use those variables to size and position Your Output. If The Variables Aren't Reinitialized WHEN The Screen Resolution Changes, Subsequent Output Might Be distorted.
Figures 15-2. The Palettedemo Application.
Palettedemo.hclass CMYAPP: Public CWINAPP
{
PUBLIC:
Virtual Bool InitInstance ();
}
Class CMainWindow: Public CFrameWnd
{
protected:
CPALETTE M_PALETTE; VOID DOGRADIENTFILL (CDC * PDC, LPRECT Prect);
Void DodrawText (CDC * PDC, LPRECT Prect);
PUBLIC:
CMAINWINDOW ();
protected:
AFX_MSG Int Oncreate (LPCReatestruct LPCS);
AFX_MSG BOOL OneRaseBkGnd (CDC * PDC);
AFX_MSG void onpaint ();
AFX_MSG BOOL ONQUERYNEWPALETTE ();
AFX_MSG Void Onpalettechanged (CWND * PfocusWnd);
Declare_message_map ()
}
Palettedemo.cpp # incrude
#include "palettedemo.h"
CMYAPP myApp;
/
// CMYAPP Member Functions
Bool CmyApp :: InitInstance ()
{
m_pmainwnd = new cmainwindow;
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
Return True;
}
/
// CMainWindow Message Map and Member Functions
Begin_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_CREATE ()
ON_WM_ERASEBKGND ()
ON_WM_PAINT ()
ON_WM_QUERYNEWPALETTE ()
ON_WM_PALETTECHANGED ()
END_MESSAGE_MAP ()
CMAINWINDOW :: CMAINWINDOW ()
{
Create (NULL, _T ("Palette Demo");
}
INT CMAINWINDOW :: OnCreate (lpcreatestruct lpcs)
{
IF (cframewnd :: oncreate (lpcs) == -1)
Return -1;
//
// CREATE A LOGICAL PALETTE IF RUNNING ON A Palettized Adapter.
//
CClientDC DC (this);
IF (DC.GetDeviceCaps (RasterCaps) & rc_palette) {
Struct {
Logpalette lp;
Paletteentry APE [63];
} PAL;
Logpalette * PLP = (logpalette *) & Pal;
PLP-> paversion = 0x300;
PLP-> PALNUMENTRIES = 64;
For (int i = 0; i <64; i ) {
PLP-> Palpalentry [i] .pered = 0;
PLP-> Palpalentry [i] .pegreen = 0;
PLP-> PALPALENTRY [I] .peblue = 255 - (i * 4);
PLP-> Palpalent [I] .peflags = 0;
}
m_palette.createpalette (PLP);
}
Return 0;
}
Bool cmainwindow :: OneRaseBkGnd (CDC * PDC)
{
CRECT RECT;
GetClientRect (& RECT);
CPALETTE * POLDPALETTE; if ((HPALETTE) m_palette! = Null) {
Poldpalette = PDC-> SelectPalette (& M_Palette, False);
PDC-> RealizePalette ();
}
DOGRADIENTFILL (PDC, & Re);
IF ((HPALETTE) m_palette! = null)
PDC-> SELECTPALETTE (POLDPALETTE, FALSE);
Return True;
}
Void cmainwindow :: onpaint ()
{
CRECT RECT;
GetClientRect (& RECT);
CPAINTDC DC (this);
DodrawText (& DC, & RECT);
}
Bool cmainwindow :: ONQUERYNEWPALETTE ()
{
IF (HPALETTE) m_palette == null) // Shouldn't happen, but
Return 0; // let's be sure.
CClientDC DC (this);
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette, False);
Uint ncount;
IF (ncount = DC.RealizePalette ())
Invalidate ();
Dc.selectPalette (Poldpalette, False);
Return ncount;
}
Void CMainWindow :: OnPalettechanged (CWND * PfocusWnd)
{
IF (HPALETTE) m_palette == null) // Shouldn't happen, but
Return; // let's be sube.
IF (pfocusWnd! = this) {
CClientDC DC (this);
CPALETTE * POLDPALETTE = DC.SelectPalette (& M_Palette, False);
IF (DC.RealizePalette ())
Invalidate ();
Dc.selectPalette (Poldpalette, False);
}
}
Void CMainWindow :: DOGRADIENTFILL (CDC * PDC, LPRECT Prect)
{
CBRUSH * PBRUSH [64];
For (int i = 0; i <64; i )
PBRUSH [I] = New CBRUSH (Palettergb (0, 0, 255 - (i * 4)))))
INT nwidth = prect-> Right - prect-> left;
INT nheight = prect-> bottom - prect-> top;
CRECT RECT;
For (i = 0; i Rect.seTRECT (0, I, NWIDTH, I 1); PDC-> FillRect (& Rect, PBRUSH [(i * 63) / nHEight]); } For (i = 0; i <64; i ) Delete Pbrush [I]; } Void CMainWindow :: DODRAWTEXT (CDC * PDC, LPRECT Prect) { CFONT font; Font.createPointFont (720, _T ("COMIC SANS MS")); PDC-> setbkmode (transparent); PDC-> SetTextColor (RGB (255, 255, 255)); Cfont * PoldFont = PDC-> SelectObject (& font); PDC-> DrawText (_T ("Hello, MFC"), -1, prect, dt_singlex | DT_Center | DT_VCENTER); PDC-> SELECTOBJECT (POLDFONT); } Palette Animation One of the more novel uses for a logical palette is for performing palette animation. Conventional computer animation is performed by repeatedly drawing, erasing, and redrawing images on the screen. Palette animation involves no drawing and erasing, but it can make images move just the same. A classic example of palette animation is a simulated lava flow that cycles shades of red, orange, and yellow to produce an image that resembles lava flowing down a hill. What's interesting is that the image is drawn only once. The illusion of motion is created by repeatedly reprogramming the system palette so that red becomes orange, orange becomes yellow, yellow becomes red, and so on. Palette animation is fast because it does not involve moving any pixels. A simple value written to a palette register on a Video Adapter Can Change The Color of An Entire Screen Full of Pixels in The BLINK OF An Eye-To Be Precise, In The 1/60 of a Second Or So It Takes for a Monitor's Electron Guns To Complete One S Creen Refresh Cycle. What Does It Take to Do Palette Animation In Windows? Just these Three Steps: Call GetDeviceCaps, and check RC_PALETTE to verify that palettes are supported. Palette animation will not work if the RC_PALETTE bit is not set. Create a logical palette containing the colors you want to animate, and mark each palette entry with a PC_RESERVED flag. Only palette entries marked PC_RESERVED can be used for palette animation. Draw an image using colors in the logical palette, and then call CPalette :: AnimatePalette repeatedly to change the palette colors. Each time you change the palette with AnimatePalette, the colors in the image Will Change Accordingly.figure 15-3. The LivePalette Window. The LivePalette application in Figure 15-3 and Figure 15-4 demonstrates how palette animation works. The window background is painted with bands of color (eight different colors in all) from PC_RESERVED entries in a logical palette. Brush colors are specified with PALETTEINDEX values . PALETTERGB values would work, too, but ordinary RGB values would not because pixels whose colors will be animated must be painted with colors marked PC_RESERVED in the logical palette, not static colors. LivePalette sets a timer to fire every 500 milliseconds, and OnTimer Animates the Palette as Follows: Paletteentry PE [8]; M_Palette.getPaletteentries (7, 1, PE); M_Palette.GetPaletteentries (0, 7, & PE [1]); m_palette.animatePalette (0, 8, PE); The calls to CPalette :: GetPaletteEntries initialize an array of PALETTEENTRY structures with values from the logical palette and simultaneously rotate every color up one position so that color 7 becomes color 0, color 0 becomes color 1, and so on. AnimatePalette then updates the colors on the screen by copying the values from the array directly to the corresponding entries in the system palette. It is not necessary to call RealizePalette because the equivalent of a palette realization has already been performed.The remainder of the program is very similar to the previous section's PaletteDemo program, with one notable exception: If RC_PALETTE is NULL, InitInstance displays a message box informing the user that palette animation is not supported in the present environment and shuts down the application by returning FALSE You'll see this message if. You Run LivePalette in Anything Other Than A 256-Color Video Mode. Figure 15-4. The LivePalette Application. LivePalette.hclass CMYAPP: Public CWINAPP { PUBLIC: Virtual Bool InitInstance (); } Class CMainWindow: Public CFrameWnd { protected: CPALETTE M_PALETTE; Void DobkGndfill (CDC * PDC, LPRECT Prect); Void DodrawText (CDC * PDC, LPRECT Prect); PUBLIC: CMAINWINDOW (); protected: AFX_MSG Int Oncreate (LPCReatestruct LPCS); AFX_MSG BOOL OneRaseBkGnd (CDC * PDC); AFX_MSG void onpaint (); AFX_MSG Void Ontimer (uint ntimerid); AFX_MSG BOOL ONQUERYNEWPALETTE (); AFX_MSG Void Onpalettechanged (CWND * PfocusWnd); AFX_MSG void onDestroy (); Declare_message_map () } Livepalette.cpp # include #include "livepalette.h" CMYAPP myApp; / // CMYAPP Member Functions Bool CmyApp :: InitInstance () { // // Verify That The Host System Is Running in a Palettized Video Mode.// CClientDC DC (NULL); IF ((DC.GetDeviceCaps (rastercaps) & rc_palette) == 0) { AfxMessageBox ("Palette Animation IS Not Supported on this" Device. Set The Color Depth to 256 Colors and Try Again. "), MB_ICONSTOP | MB_OK); Return False; } // // Initialize the application as Normal. // m_pmainwnd = new cmainwindow; m_pmainwnd-> showwindow (m_ncmdshow); m_pmainwnd-> UpdateWindow (); Return True; } / // CMainWindow Message Map and Member Functions Begin_MESSAGE_MAP (CMainWindow, CFrameWnd) ON_WM_CREATE () ON_WM_ERASEBKGND () ON_WM_PAINT () ON_WM_TIMER () ON_WM_QUERYNEWPALETTE () ON_WM_PALETTECHANGED () ON_WM_DESTROY () END_MESSAGE_MAP () CMAINWINDOW :: CMAINWINDOW () { Create (NULL, _T ("Palette Animation Demo")); } INT CMAINWINDOW :: OnCreate (lpcreatestruct lpcs) { Static Byte Bcolorvals [8] [3] = { 128, 128, 128, // dark gray 0, 0, 255, // blue 0, 255, 0, // Green 0, 255, 255, // cyan 255, 0, 0, // RED 255, 0, 255, // magenta 255, 255, 0, // Yellow 192, 192, 192 // light gray } IF (cframewnd :: oncreate (lpcs) == -1) Return -1; // // CREATE A Palette to Support Palette Animation. // Struct { Logpalette lp; Paletteentry APE [7]; } PAL; Logpalette * PLP = (logpalette *) & Pal; PLP-> paversion = 0x300; PLP-> PALNUMENTRIES = 8; For (int i = 0; i <8; i ) { PLP-> Palpalent [i] .pled = bcolorvals [i] [0]; PLP-> Palpalent [i] .pegreen = bcolorvals [i] [1]; PLP-> Palpalent [i] .peblue = bcolorvals [i] [2]; PLP-> PALPALENTRY [I] .peflags = pc_reserved; } M_Palette.createPalette (PLP); // // Program a Timer to Fire Every Half-Second. // Settimer (1, 500, null); Return 0; } Void CMainWindow :: ONTIMER (Uint Ntimerid) { Paletteentry PE [8]; M_Palette.getPaletteentries (7, 1, PE); M_Palette.GetPaletteentries (0, 7, & PE [1]); m_palette.animatePalette (0, 8, PE); } Bool cmainwindow :: OneRaseBkGnd (CDC * PDC) { CRECT RECT; GetClientRect (& RECT); CPALETTE * POLDPALETTE; Poldpalette = PDC-> SelectPalette (& M_Palette, False); PDC-> RealizePalette (); DobkGndfill (PDC, & Re); PDC-> SELECTPALETTE (POLDPALETTE, FALSE); Return True; } Void cmainwindow :: onpaint () { CRECT RECT; GetClientRect (& RECT); CPAINTDC DC (this); DodrawText (& DC, & RECT); } Bool cmainwindow :: ONQUERYNEWPALETTE () { CClientDC DC (this); Dc.selectPalette (& M_Palette, False); Uint ncount; IF (ncount = DC.RealizePalette ()) Invalidate (); Return ncount; } Void CMainWindow :: OnPalettechanged (CWND * PfocusWnd) { IF (pfocusWnd! = this) { CClientDC DC (this); Dc.selectPalette (& M_Palette, False); IF (DC.RealizePalette ()) Invalidate (); } } Void cmainwindow :: ONDESTROY () { Killtimer (1); } Void CMainWindow :: DobkGndfill (CDC * PDC, LPRECT Prect) { CBRUSH * PBRUSH [8]; For (int i = 0; i <8; i ) PBRUSH [I] = New CBRUSH (PaletteIndex (i)); INT nwidth = prect-> Right - prect-> left; INT NHEIGHT = (prect-> bottom - prect-> top) / 8; CRECT RECT; INT Y1, Y2; For (i = 0; i <8; i ) { Y1 = i * nheight; Y2 = (i == 7)? prect-> bottom - prect-> top: y1 nheight; Rect.seTRECT (0, Y1, NWIDTH, Y2); PDC-> FillRect (& Rect, PBRUSH [I]); } For (i = 0; i <8; i ) delete PBRUSH [I]; } Void CMainWindow :: DODRAWTEXT (CDC * PDC, LPRECT Prect) { CFONT font; Font.createPointFont (720, _T ("COMIC SANS MS")); PDC-> setbkmode (transparent); PDC-> SetTextColor (RGB (255, 255, 255)); Cfont * PoldFont = PDC-> SelectObject (& font); PDC-> DrawText (_T ("Hello, MFC"), -1, prect, dt_singlex | DT_Center | DT_VCENTER); PDC-> SELECTOBJECT (POLDFONT); } The: setsystempaletteuse function A final word on palette usage: if your application absolutely, unequivocally has to have access to the entire system palette and not just the unused color entries that remain after the static colors are added, it can call :: SetSystemPaletteUse with a device context handle and a SYSPAL_NOSTATIC parameter to reduce the number of static colors from 20 to 2-black and white. On a 256-color video adapter, this means that 254 instead of just 236 colors can be copied from a logical palette to the system palette. The Win32 API documentation makes it pretty clear how :: SetSystemPaletteUse and its companion function :: GetSystemPaletteUse are used, so I'll say no more about them here. However, realize that replacing the static colors with colors of your own is an extremely unfriendly thing to DO BECAUSE IT COULD CORRUPT The Colors of Title Bars, Push Buttons, And Other Window Elements Throughout The Entire System. Don't do it unless you have to.