First, we have to define two variables of type XColor:
XColor redx, reds;We need two variables for a single color. To allocate a color, we call the function XAllocNamedColor. This can be done in any point of the program, after that the display has been opened.
/* allocate the red color */ XAllocNamedColor(dpy, DefaultColormapOfScreen(DefaultScreenOfDisplay(dpy)), "red", &reds, &redx);To change the foreground color, we call XSetForeground, passing reds.pixel as an argument. This function sets the foreground color of a graphic context.
/* set foreground color */ XSetForeground(dpy, g, reds.pixel);After this, any drawing function (such as XFillRectangle) called with the graphic context g will draw in red, until the foreground color of g is changed again. Each color needs to be allocated only once, while the foreground color may be changed as many times as needed.
The module coloredsquares.c allocates an array of colors, and then choose a different color for each square.
To compile, test, and install, see: testing and installing a new module