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

ListBox 程式設計兩例:水平捲軸與圖示項目 (OwnerDraw)

     編輯:VC 教學

例一:啟用水平捲軸

TListBox 預設無水平捲軸。發送 LB_SETHORIZONTALEXTENT 訊息設定水平捲動範圍 (像素),即可在項目過寬時顯示捲軸。

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

建議在 FormCreate 或項目加入後呼叫。

例二:OwnerDraw 繪製圖示 + 文字

步驟

  1. 設定 ListBox1->Style = lbOwnerDrawVariable。
  2. 放置 TImageList (名為 ImageList1) 載入圖示。
  3. 實作 OnMeasureItem 決定項目高度。
  4. 實作 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 原生支援,無需第三方元件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved