Bits = GetDeviceCaps(screenDC, BITSPIXEL);
DeleteDC(screenDC);
if (numOfBits == 16)
{
// 是否为64K色,或32K
WORD red, green, blue;
GetScrRGBBitsPerPixel(&red, &green, &blue);
if (red == 32 && green == 32 && blue == 32)
// 32*32*32 = 2^15 色
numOfBits = 15;
}
return numOfBits;
}
GetScrRGBBitsPerPixel()通过255次循环测
试设备支持的红、绿色和蓝色值。
BOOL GetScrRGBBitsPerPixel(WORD* pRedBits,
WORD* pGreenBits,
WORD* pBlueBits)
{
BOOL isError = FALSE;
HDC screenDC, memDC;
HBITMAP bmp = NULL;
HBITMAP bmpOld = NULL;
*pRedBits = *pGreenBits = *pBlueBits = 1;
screenDC = CreateDC("DISPLAY", NULL,
NULL, NULL);
memDC = CreateCompatibleDC(NULL);
bmp = CreateCompatibleBitmap(screenDC, 1, 1);
isError = screenDC && memDC && bmp;
if (!isError)
goto CleanUp;
/* 有时goto语句是处理出错的一种很简便的方法 */
bmpOld = (HBITMAP)SelectObject(memDC, bmp);
{
COLORREF oldColor;
COLORREF curColor = RGB(255, 255, 255);
int n;
for (n = 255; n >= 0; --n)
{
oldColor = curColor;
curColor = SetPixel(memDC,
0, 0, RGB(n, n, n));
isError = curColor;
if (isError == CLR_INVALID)
{
isError = TRUE;
goto CleanUp;
}
/* 计算红、绿和蓝匹配情况 */
if (GetRvalue(curColor)
< GetRvalue(oldColor))
++(*pRedBits);
if (GetGvalue(curColor)
< GetGvalue(oldColor))
++(*pGreenBits);
if (GetBvalue(curColor)
< GetBvalue(oldColor))
++(*pBlueBits);
}
}
CleanUp:
if (bmpOld)
DeleteObject(bmpOld);
if (bmp)
DeleteObject(bmp);
if (isError)
*pRedBits = *pGreenBits
= *pBlueBits = 0;
if (screenDC)
DeleteDC(screenDC);
if (memDC)
DeleteDC(memDC);
return !isError;
}
---- 可见GetScrRGBBitsPerPixel()不仅是解决本问题的核心,而且还可得到正使用的红色、绿色和蓝色各自的位数。例如,当有16位颜色时,哪一个颜色获得6位,而不是另二个的5位,你可通过测试发现,一般绿色成分多一些。