應用程式需根據系統顏色深度 (8-bit/256色、16-bit/高色、24/32-bit/真彩色) 調整 UI 渲染策略、圖片載入格式或繪圖優化。Delphi 無內建屬性直接提供此資訊,需呼叫 Win32 API。
function GetSysColorNum: Integer;
var
ScreenDC: HDC;
BitsPixel: Integer;
begin
Result := 0;
ScreenDC := GetDC(0); // 取得螢幕 DC (0 = 整個螢幕)
try
BitsPixel := GetDeviceCaps(ScreenDC, BITSPIXEL); // 每像素位元數
Result := 1 shl BitsPixel; // 2^BitsPixel = 顏色總數
finally
ReleaseDC(0, ScreenDC); // 必須釋放 DC
end;
end;
| BitsPixel | 顏色數 (Result) | 常見模式名稱 |
|---|---|---|
| 1 | 2 | 單色 |
| 4 | 16 | 16 色 (VGA) |
| 8 | 256 | 256 色 (調色盤) |
| 16 | 65,536 | 高色 (High Color) |
| 24 | 16,777,216 | 真彩色 (True Color) |
| 32 | 4,294,967,296 | 增強真彩色 (含 Alpha 通道) |
function IsTrueColorSupported: Boolean;
begin
Result := GetSysColorNum >= 65536; // 至少 16-bit
end;
// 根據顏色深度載入不同資源
procedure LoadAppropriateResources;
begin
case GetSysColorNum of
256: LoadPaletteBasedUI; // 8-bit 調色盤模式
65536: LoadHighColorResources; // 16-bit
else LoadTrueColorResources; // 24/32-bit
end;
end;
GetDeviceCaps(DC, PLANES):色板平面數GetDeviceCaps(DC, NUMCOLORS):調色盤條目數 (僅調色盤模式有效)GetDeviceCaps(DC, HORZRES)/VERTRES:螢幕解析度 (像素)GetDeviceCaps(DC, LOGPIXELSX):水平 DPI (通常 96, 120, 144...)GetDC(0) 取得主顯示器 DC。多螢幕系統下不同顯示器可能有不同色深 (極少見),需使用 EnumDisplayMonitors 逐一檢測。
單一 API 組合即可可靠取得系統顏色深度,為自適應 UI 渲染提供決策依據。現代系統幾乎皆為 32-bit 真彩色,但嵌入式、遠端桌面、虛擬機環境仍可能遇到低色深情境,保留此檢測邏輯可提升軟體健壯性。