CreatePalette
Header: wingdi.h
Library: gdi32.lib
Syntax
HPALETTE CreatePalette(
const LOGPALETTE *lpLogPalette
);
Parameters
| lpLogPalette | Pointer to a LOGPALETTE structure that defines the logical palette. |
|---|
Return Value
If the function succeeds, the return value is a handle to the logical palette. If the function fails, the return value is NULL. Use GetLastError for extended error information.
Remarks
- The created palette can be selected into a device context with
SelectPaletteand realized withRealizePalette. - When a process terminates, all GDI objects it created are automatically deleted.
- Only palette-based devices (e.g., 8‑bit displays) use palettes; on true‑color displays the function still works but the palette is ignored.
Example
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
LOGPALETTE *pLogPal;
HPALETTE hPal;
// Allocate palette memory for 256 colors
pLogPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + 255 * sizeof(PALETTEENTRY));
pLogPal->palVersion = 0x300;
pLogPal->palNumEntries = 256;
// Initialize the palette entries (simple grayscale)
for (int i = 0; i < 256; ++i) {
pLogPal->palPalEntry[i].peRed = (BYTE)i;
pLogPal->palPalEntry[i].peGreen = (BYTE)i;
pLogPal->palPalEntry[i].peBlue = (BYTE)i;
pLogPal->palPalEntry[i].peFlags = 0;
}
hPal = CreatePalette(pLogPal);
if (!hPal) {
MessageBox(NULL, L"Failed to create palette", L"Error", MB_ICONERROR);
return 0;
}
// Normally you would select the palette into a DC here
// ...
// Clean up
DeleteObject(hPal);
free(pLogPal);
return 0;
}