Enumerating colors

Recently for one tiny GDI application I needed to create an array of solid pens of different colors.
One pen for each color: red, yellow, blue, green, etc…

First I tried to play with 32 bit color space and RGB color encoding to get different color values but soon I found that MSDN has an example of enumerating
colors for a given device context.

For details see “Enumerating Colors” MSDN example.

Finally I came to create a slightly simpler code which creates an array of pens, that I needed.
It also uses EnumObjects function but the callback routine is changed.


//Somewhere define a global variable to contain all pens
HPEN * hPens;

//===============================================
//Callback function for enumerating colors
//===============================================
void CALLBACK ColorsEnumProc(LPVOID lp, LPBYTE lpb){
	LPLOGPEN lopn;
	int  * pIndex = (int*) lpb;

	lopn = (LPLOGPEN)lp;
	if (lopn->lopnStyle==PS_SOLID){
		hPens[*pIndex] = CreatePen(PS_SOLID, 1, lopn->lopnColor);
	}
	(*pIndex)++;
}

//===============================================
//Enumeration is simple

	HDC hdc = GetWindowDC(hWnd);

//Get the number of colors.
	int cNumberOfColors = GetDeviceCaps(hdc, NUMCOLORS);

//This index will be changed to properly index different pens
	int Index = 0;

//Allocate pen handles
	hPens = new HPEN[cNumberOfColors];

//Enumerate all pens and save solid colors in the array.
	EnumObjects(hdc, OBJ_PEN, (GOBJENUMPROC) ColorsEnumProc, (LONG) &Index);


Now hPens contains handles to pens of different colors.
Don’t forget to free resources when you finish working with pens.

	//release window dc
	ReleaseDC(hWnd, hdc);

	//free GDI resources for each pen
	for(int i=0; i<cNumberOfColors; ++i){
		DeleteObject((HGDIOBJ) hPens[i]);
	}

	//free memory allocated to pens array
	delete [] hPens;

Leave a Reply