Link to home
Start Free TrialLog in
Avatar of Ofer Leshem
Ofer LeshemFlag for Israel

asked on

Delphi - count visible lines on TListBox

How can I count how much lines are visible in the same time on specific listbox. The user have the ability to change the font size, so I need to know how many lines are visible in any font size.
Avatar of Thommy
Thommy
Flag of Germany image

Try this...
function TListBox.VisibleLines: Integer;
begin
  Result := Height div (Abs(Self.Font.Height) + 2);
end;

Open in new window

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


function ListBoxItemsVisible( aListBox : TListBox ) : Integer;
begin

     result := round (aListBox.ClientHeight /  aListBox.ItemHeight) ;

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
       edit1.Text := IntToStr( ListBoxItemsVisible(ListBox1));
end;

end
ASKER CERTIFIED SOLUTION
Avatar of jimyX
jimyX

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Demo project...
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen }
    function VisibleLines(AListBox:TListBox): Integer;
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.VisibleLines(AListBox:TListBox): Integer;
begin
  Result := AListBox.Height div (Abs(AListBox.Font.Height) + 2);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(inttostr(VisibleLines(ListBox1)));
end;

end.

Open in new window

a bit spice it up:

function ListBoxItemsVisible( aListBox : TListBox ) : Integer;
var    MaxItems   : Integer ;
begin

     MaxItems := aListBox.Items.Count;

     result := round (aListBox.ClientHeight /  aListBox.ItemHeight) ;

     
     if result > MaxItems then result := MaxItems;   //  if ListBox not full, report the count of items inside the box


end;