Creating Colored Pens and Brushes

Although you can specify any color for a pen when creating it, the system uses only colors that are available on the device. This means the system uses the closest matching color when it realizes the pen for drawing. When creating brushes, the system generates a dithered color if you specify a color that the device does not support. In either case, you can use the RGB macro to specify a color when creating a pen or brush.

// DrawARectangle - draws a red rectangle with a green border
// No return value.
// hdc - handle of the device context

void DrawARectangle(HDC hdc) 
{
    HPEN hpen, hpenOld;
    HBRUSH hbrush, hbrushOld;

    // Create a green pen.
    hpen = CreatePen(PS_SOLID, 10, RGB(0, 255, 0));
    // Create a red brush.
    hbrush = CreateSolidBrush(RGB(255, 0, 0));

    // Select the new pen and brush, and then draw.
    hpenOld = SelectObject(hdc, hpen);
    hbrushOld = SelectObject(hdc, hbrush);
    Rectangle(hdc, 100,100, 200,200);

    // Do not forget to clean up.
    SelectObject(hdc, hpenOld);
    DeleteObject(hpen);
    SelectObject(hdc, hbrushOld);
    DeleteObject(hbrush);
}