首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何基于TListBox.OnDrawItem属性在TListBox.TabWidth事件中扩展制表符?

如何基于TListBox.OnDrawItem属性在TListBox.TabWidth事件中扩展制表符?
EN

Stack Overflow用户
提问于 2014-06-10 06:26:53
回答 2查看 858关注 0票数 3

我正在使用德尔菲XE4和下面的是我的示例应用程序。

代码语言:javascript
复制
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
        State: TOwnerDrawState);
  public
    procedure AfterConstruction; override;
  end;

var
  Form1: TForm1;

implementation

uses System.Math;

{$R *.dfm}

procedure TForm1.AfterConstruction;
begin
  inherited;
  ListBox1.Style := lbOwnerDrawVariable;

  ListBox1.Items.Add('o'#9'Line 1');
  ListBox1.Items.Add('o'#9'Line 2');
  ListBox1.Items.Add('o'#9'Line 3');
  ListBox1.Items.Add('o'#9'Line 4');
  ListBox1.Items.Add('o'#9'Line 5');
end;

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect:
    TRect; State: TOwnerDrawState);
const C: array[boolean] of TColor = (clRed, clGreen);
var L: TListBox;
    S: string;
    iTextHeight: integer;
begin
  L := Control as TListBox;
  L.Canvas.Font.Color := C[Index < 2];

  S := L.Items[Index];

  iTextHeight := Max(Rect.Height, L.Canvas.TextHeight(S) + 2);
  SendMessage(L.Handle, LB_SETITEMHEIGHT, Index, iTextHeight);
  Rect.Height := iTextHeight;
  L.Canvas.FillRect(Rect);

  L.Canvas.TextOut(Rect.Left, Rect.Top + 1, S);
end;

end.

使用TListBox.OnDrawItem事件的目的是在我的实际应用程序中显示一些不同字体颜色的项目。有没有任何方法来扩展TListBox.DrawItem事件中基于TListBox.TabWidth的制表符字符?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-11 08:46:09

这个密码适用于我。

代码语言:javascript
复制
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect:
    TRect; State: TOwnerDrawState);
var //...
    P: TDrawTextParams;
begin
  //...

  P.cbSize := SizeOf(P);
  P.iTabLength := 5;
  P.iLeftMargin := 0;
  P.iRightMargin := 0;
  DrawTextEx(L.Canvas.Handle, PChar(S), S.Length, Rect, DT_EXPANDTABS or DT_TABSTOP, @P);
end;
票数 1
EN

Stack Overflow用户

发布于 2014-06-10 07:19:32

我会做这样的事。基本上,使用选项卡的宽度来计算应该在什么地方画东西。下面的代码将替换上一次TextOut调用。我正在去掉选项卡,每当我遇到一个选项卡时,我就会将输出缩进列表框选项卡的宽度:

代码语言:javascript
复制
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect:
    TRect; State: TOwnerDrawState);
var 
  LeftIndent: Integer;
begin
  ...

  LeftIndent := 0;
  while Pos(#9,S) > 0 do
  begin
    L.Canvas.TextOut(Rect.Left + LeftIndent, Rect.Top + 1, Copy(S, 1, Pos(#9,S)-1));
    Delete(S, 1, Pos(#9,S));
    LeftIndent := LeftIndent + L.TabWidth;
  end;
  L.Canvas.TextOut(Rect.Left + LeftIndent, Rect.Top + 1, S);
end;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24134252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档