Right justify ListBox items

The default ListBox items alignment is LeftJustify. There is no Object Inspector property to change this, so if we need to right justify items, we must use a simple trick.

First, set the Style property to lbOwnerDrawFixed, then use the following code as OnDrawItem event:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); 
var 
  l: Integer;  
  t: String; 
begin 
  with ListBox1 do 
  begin 
    Canvas.FillRect(Rect); 
    t := Items[Index];  
    l := Rect.Right - Canvas.TextWidth(t) - 1; 
    Canvas.TextOut(l, Rect.Top, t); 
  end; 
end;

Leave a Reply