發送 LB_SETHORIZONTALEXTENT 設定水平捲動範圍 (像素),超過寬度的項目即可水平捲動。
SendMessage(ListBox1->Handle, LB_SETHORIZONTALEXTENT,
ListBox1->Width + 32, 0);
設定 Style = lbOwnerDrawVariable,處理 OnMeasureItem 決定項目高度,OnDrawItem 繪製圖示與文字。
const int margin = 2; // 圖示邊距
void __fastcall TForm1::ListBox1MeasureItem(TWinControl *Control, int Index,
int &Height)
{
Height = ImageList1->Height + margin * 2;
}
void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
TRect &Rect, TOwnerDrawState State)
{
// 填滿背景
ListBox1->Canvas->FillRect(Rect);
// 繪製圖示
ImageList1->Draw(ListBox1->Canvas, Rect.Left + margin, Rect.Top + margin, Index);
// 繪製文字 (垂直置中)
String text = ListBox1->Items->Strings[Index];
int off = (Rect.Bottom - Rect.Top - ListBox1->Canvas->TextHeight(text)) / 2;
ListBox1->Canvas->TextOut(
Rect.Left + ImageList1->Width + 2 * margin,
Rect.Top + off, text);
}
ImageList1 需預先加入圖示,數量與 ListBox 項目數對應。lbOwnerDrawVariable 允許每項高度不同;若高度固定可用 lbOwnerDrawFixed 並省略 OnMeasureItem。