70.2.1 Creating a Colored Pen

You can use the ChooseColor common dialog box to let the user choose pen, brush, and text colors. This dialog box is displayed by initializing a CHOOSECOLOR data structure and then calling the ChooseColor function. Upon executing successfully, the ChooseColor function stores an RGB triplet corresponding to the user's selection in the rgbResult member of the CHOOSECOLOR data structure.You can use this member to specify a pen, brush, or text color by calling the CreatePenIndirect, CreateBrushIndirect, or SetTextColor functions and copying the RGB data from this member to the appropriate argument.

In the following example, the data contained in the rgbResult member is copied into the lopnColor member of a LOGPEN data structure and used to create a new pen:

case IDM_PENCOLOR:

/* Retrieve the default logical palette entries. */

iRet = GetPaletteEntries(hpal, 0, 20, ape);

/* Set the custom color controls to white. */

for (i = 0; i < 16; i++)

aclrCust[i] = RGB(255, 255, 255);

/* Initialize clr to black. */

clr = RGB(0, 0, 0);

/* Set all structure fields to zero. */

memset(&cc, 0, sizeof(CHOOSECOLOR));

/* Initialize the necessary CHOOSECOLOR members. */

cc.lStructSize = sizeof(CHOOSECOLOR);

cc.hwndOwner = hWnd;

cc.rgbResult = clr;

cc.lpCustColors = aclrCust;

cc.Flags = CC_PREVENTFULLOPEN;

if (ChooseColor(&cc)) {

/* Initialize the LOGPEN structure. */

lp.lopnStyle = PS_SOLID;

lp.lopnWidth.x = 1;

lp.lopnColor = cc.rgbResult;

/* Select the new pen and draw. */

hdc = GetDC(hWnd);

hpenOld = SelectObject(hdc, CreatePenIndirect(&lp));

MoveToEx(hdc, 100, 100, NULL);

LineTo(hdc, 100, 200);

/* . */

/* . */

/* . */

ReleaseDC(hWnd, hdc);

}

break;