TListBox 預設無水平捲軸。發送 LB_SETHORIZONTALEXTENT 訊息設定水平捲動範圍 (像素),即可在項目過寬時顯示捲軸。
SendMessage(ListBox1->Handle, LB_SETHORIZONTALEXTENT, ListBox1->Width + 32, 0);
建議在 FormCreate 或項目加入後呼叫。
ListBox1->Style = lbOwnerDrawVariable。TImageList (名為 ImageList1) 載入圖示。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)
{
// 1. 填充背景
ListBox1->Canvas->FillRect(Rect);
// 2. 繪製圖示 (置中垂直對齊)
int imgY = Rect.Top + MARGIN;
ImageList1->Draw(ListBox1->Canvas, Rect.Left + MARGIN, imgY, Index);
// 3. 繪製文字 (垂直置中於圖示右側)
String txt = ListBox1->Items->Strings[Index];
int txtH = ListBox1->Canvas->TextHeight(txt);
int txtY = Rect.Top + (Rect.Height() - txtH) / 2;
int txtX = Rect.Left + ImageList1->Width + 2 * MARGIN;
ListBox1->Canvas->TextOut(txtX, txtY, txt);
}
此法可構建帶圖示的選單、工具列等介面,完全由 VCL 原生支援,無需第三方元件。