Listing 1  Initializing and Installing
           a Logical Palette


/* Global Variables: */

struct xLOGPALETTE
{
 WORD         palVersion;
 WORD         palNumEntries;
 PALETTEENTRY palPalEntry[256];
} logpal;

HPALETTE newPalette = NULL;
HPALETTE oldPalette = NULL;
WORD oldPaletteUsage = 0xFFFF;

#define FOREGROUND 0

/*--------------------------------------------------*/

int FAR PASCAL SetGrayScalePalette (hWnd)
/*
  This function initializes and installs a gray
  scale palette into the system palette.
*/
  HWND hWnd;

  {
   int result,i;
   HDC hDC;

   result = NO_ERROR;

   if (newPalette == NULL)
   {
    /* Initialize logical palette: */
    logpal.palVersion = 0x0300;
    logpal.palNumEntries = 256;

    for (i = 0; i < 256; i++)
    {
     logpal.palPalEntry[i].peRed = (BYTE)i;
     logpal.palPalEntry[i].peGreen = (BYTE)i;
     logpal.palPalEntry[i].peBlue = (BYTE)i;
     logpal.palPalEntry[i].peFlags = 0;
    }

    /* Create new palette: */
    newPalette = CreatePalette((LPLOGPALETTE)&logpal);
    if (newPalette != NULL)
    {
     hDC = GetDC(hWnd);
     if (hDC != NULL)
     {
      /* Select new palette; save current palette: */
      oldPalette = SelectPalette(hDC,
                                 newPalette,
                                 FOREGROUND);
      if (oldPalette != NULL)
      {
       /*
         This call sets the use of the 20 static
         colors in the system palette. In this case,
         these colors are preserved in the new
         palette (SYSPAL_STATIC).
       */
       oldPaletteUsage = SetSystemPaletteUse(hDC,
                                      SYSPAL_STATIC);

       /*
         The call to UnrealizeObject instructs GDI
         to treat the specified palette as if it were
         never before submitted to GDI. As a result,
         when RealizePalette is then called, the GDI
         will remap the entire system palette using
         the new logical palette.
       */
       UnrealizeObject(newPalette);
       RealizePalette(hDC);
      }
      else result = PAL_SELECT_ERROR;

      ReleaseDC(hWnd,hDC);
     }
     else result = PAL_HDC_ERROR;

     if (result != NO_ERROR) DeleteObject(newPalette);
    }
    else result = PAL_CREATE_ERROR;
   }

   return result;
  } /* SetGrayScalePalette */

