Retrieving the real color depth

Did you ever need to find out from your Windows application, on what color depth it's running? If yes, you will probably have used something like

bpp = GetDeviceCaps(GetDC(NULL), BITSPIXEL);


But what about 16 bpp vs 15 bpp? MSDN says in both cases 16 is returned. So this function isn't useful to get the real color depth. It's a little more complicated. Here's a function that allows you to get the real color depth. Based on SDL code, Copyright (C) 1997-2006 Sam Lantinga.


ULONG
GetRealColorDepth()
{
HBITMAP hbmp;
HDC hdc;
struct
{
BITMAPINFOHEADER bmiHeader;
ULONG aulMasks[3];
} bmi;
PBITMAPINFO pbmi = (PBITMAPINFO)&bmi;
ULONG ulColorDepth;

/* Get the screen DC */
hdc = GetDC(NULL);

/* Create a compatible bitmap */
hbmp = CreateCompatibleBitmap(hdc, 1, 1);

/* Fill BITMAPINFOHEADER */
memset(&bmi, 0, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
GetDIBits(hdc, hbmp, 0, 1, NULL, pbmi, DIB_RGB_COLORS);

/* Get the basic color depth */
ulColorDepth = bmi.bmiHeader.biBitCount;

/* Special case 16 bpp */
if (ulColorDepth == 16)
{
/* Call again to fill in the bitfields */
GetDIBits(hdc, hbmp, 0, 1, NULL, pbmi, DIB_RGB_COLORS);

/* Check the red mask */
if (bmi.aulMasks[0] == 0x7c00)
ulColorDepth = 15;
}

/* Cleanup and return */
DeleteObject(hbmp);
return ulColorDepth;
}