Mega Code Archive

 
Categories / Delphi / VCL
 

TListBox Tricks

Title: tListBox Tricks Question: How can you add a horizontal Scrollbar to a Listbox ? How can you move items in a ListBox with Drag and Drop (which scrolls if you reach the top or the bottom) ? Answer: * How can you add a horizontal Scrollbar to a Listbox ? SendMessage(ListBox.Handle, LB_SETHORIZONTALEXTENT, MaxWidth, 0); or simply ListBox.ScrollWidth := MaxWidth; * How can you determine the Listbox index of the topmost entry or item, which is displayed at the top of the Listbox ? TopIndex := SendMessage(ListBox.Handle, LB_GETTOPINDEX, 0, 0); or simply ListBox.TopIndex; * How can you move items in a ListBox with Drag and Drop ? 1. set DragMode on dmAutomatic 2. implement OnDragOver and OnDragDrop Events procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Sender is TListBox; end; procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var Box : tListBox; s : string; TargetIndex : integer; begin // delete selected item // and insert at new position // determined by ItemAtPos(..) Box:=TListBox(Source); s:=Box.Items[Box.ItemIndex]; Box.Items.Delete(Box.ItemIndex); TargetIndex:=Box.ItemAtPos(Point(x,y),true); Box.Items.Insert(TargetIndex,s); Box.ItemIndex:=TargetIndex; end; * How can you move items in a ListBox with Drag and Drop, which scrolls if you reach the top or the bottom ? procedure TForm1.ListBox1Click(Sender: TObject); begin // save source ItemIndex SourceIndex:=(Sender as TListBox).ItemIndex; end; procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var TargetPos : integer; Box : tListBox; r : tRect; begin Box := Sender as TListBox; TargetPos := Box.ItemAtPos(Point(x,y),True); Box.ItemIndex := TargetPos; r:=Box.ItemRect(TargetPos); if r.top begin if TargetPos 0 then Box.ItemIndex:=TargetPos-1; end else if r.bottom (Box.Height-Box.ItemHeight) then begin if TargetPos Box.ItemIndex:=Box.ItemIndex+1; end; if (TargetPos = -1) then Accept := False else Accept := True; end; procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var Box : tListBox; s : string; TargetIndex : integer; begin // delete selected item // and insert at new position // determined by ItemAtPos(..) Box:=TListBox(Source); s:=Box.Items[SourceIndex]; Box.Items.Delete(SourceIndex); TargetIndex:=Box.ItemAtPos(Point(x,y),true); Box.Items.Insert(TargetIndex,s); Box.ItemIndex:=TargetIndex; end;