CColorDialog 中顏色選擇區的每個小方塊是用什麼控制項繪製的?按鈕樣式凸起、文本框又不像,如何自行實現類似效果?
靜態文本控制項 + SS_OWNERDRAW / SS_BITMAP 樣式,或直接繼承 CStatic 重寫 OnPaint。
Owner Draw 或 Bitmap。DDX_Control 綁定 CStatic 變數,或動態 Create。OnPaint 或 DrawItem 中用 CDC::FillSolidRect 填充顏色,加 DrawEdge 畫邊框。// 範例:動態建立顏色方塊
void CMyColorPicker::CreateColorBox(int x, int y, COLORREF clr)
{
CStatic* pBox = new CStatic;
pBox->Create(_T(""), WS_CHILD | WS_VISIBLE | SS_OWNERDRAW,
CRect(x, y, x+20, y+20), this, IDC_COLOR_BASE + index);
m_boxes.Add(pBox);
m_colors.Add(clr);
}
// 訊息映射 ON_WM_DRAWITEM()
void CMyColorPicker::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDIS)
{
if (nIDCtl >= IDC_COLOR_BASE)
{
int idx = nIDCtl - IDC_COLOR_BASE;
CDC dc; dc.Attach(lpDIS->hDC);
dc.FillSolidRect(&lpDIS->rcItem, m_colors[idx]);
dc.DrawEdge(&lpDIS->rcItem, BDR_RAISEDINNER, BF_RECT);
dc.Detach();
}
}
CBitmap 預渲染含邊框的小圖,STM_SETIMAGE 切換,效能更高。核心思想:Static 控制項 + 自繪 = 無限可能的視覺元素。