August 2nd, 2019

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

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.

 

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

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

  • Neil Rashbrook

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