首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ Builder ListBox 兩個實用技巧

     編輯:關於C++

一、加入水平捲軸

發送 LB_SETHORIZONTALEXTENT 設定水平捲動範圍 (像素),超過寬度的項目即可水平捲動。

SendMessage(ListBox1->Handle, LB_SETHORIZONTALEXTENT,
    ListBox1->Width + 32, 0);

二、Owner-Draw 顯示圖示與文字

設定 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。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved