How can I extract the color from a solid color GDI brush?

Raymond Chen

Suppose you have a GDI HBRUSH and you suspect that it is a solid color brush. How can you confirm this suspicion and, if true, get the underlying color?

You can ask the Get­Object function to peek inside the brush.

COLORREF GetBrushColor(HBRUSH brush)
{
  LOGBRUSH lbr;
  if (GetObject(brush, sizeof(lbr), &lbr) != sizeof(lbr)) {
    // Not even a brush!
    return CLR_NONE;
  }
  if (lbr.lbStyle != BS_SOLID) {
    // Not a solid color brush.
    return CLR_NONE;
  }
  return lbr.lbColor;
}

Given a brush, the Get­Object function gives you basic information about the brush. The lbStyle member tells you what kind of brush you have. In our case, we are interested in solid color brushes.

If we do have a solid color brush, then the lbColor tells the underlying color.

We can run a few simple tests to confirm that this works:

  COLORREF clr;

  // This returns clr == RGB(0,0,0)
  clr = GetBrushColor((HBRUSH)GetStockObject(BLACK_BRUSH));

  // This returns clr == RGB(64,64,64)
  clr = GetBrushColor((HBRUSH)GetStockObject(DKGRAY_BRUSH));

  // This returns clr == RGB(1,2,3)
  HBRUSH brush = CreateSolidBrush(RGB(1, 2, 3));
  clr = GetBrushColor(brush);
  DeleteObject(brush);

  // This returns clr == GetSysColor(COLOR_INFOBK)
  clr = GetBrushColor(GetSysColorBrush(COLOR_INFOBK));

  // This returns clr == CLR_NONE, not a solid color brush
  clr = GetBrushColor((HBRUSH)GetStockObject(HOLLOW_BRUSH));

If you want to understand brushes that aren’t solid color brushes, you can dig into the lbHatch member. It contains additional information that describes the brush, the format of which varies depending on the lbStyle.

 

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Neil Rashbrook 0

    Has the Atom feed been discontinued? This post only appears on the other feed.

Feedback usabilla icon