Mirror

How to display the item text of a TListBox in the hint window of the listbox (Views: 71)


Problem/Question/Abstract:

I would like to have my hints read the same as the listbox item that the mouse is pointing to. How can I do that?

Answer:

Solve 1:

You could use the listboxes OnMOuseMove event together with the ItemAtPos method.


procedure TForm1.ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  item: Integer;
begin
  with Sender as TListbox do
  begin
    item := itemAtpos(Point(x, y), true);
    if item >= 0 then
    begin
      if hint <> items[item] then
      begin
        hint := items[item];
        application.cancelhint;
      end;
    end;
  end;
end;


Solve 2:

You can use the OnMouseMove event and trap which item is under the cursor.

procedure TForm1.ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  APoint: TPoint;
  Index: Integer;
begin
  APoint.X := X;
  APoint.Y := Y;
  Index := ListBox1.ItemAtPos(APoint, True);
  if Index >= 0 then
  begin
    ListBox1.Hint := ListBox1.Items.Strings[Index];
  end;
end;

If you want to Hint to change when the mouse moves after the hint is originally shown, you might want to do something like this:

Set the ShowHint property of the list box to False.


procedure TForm1.ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  APoint: TPoint;
  Index: Integer;
  HW: THintWindow;
  Rec: TRect;
  sHint: string;
begin
  APoint.X := X;
  APoint.Y := Y;
  Index := ListBox1.ItemAtPos(APoint, True);
  if Index >= 0 then
  begin
    HW := THintWindow.Create(nil);
    try
      GetCursorPos(APoint);
      sHint := ListBox1.Items.Strings[Index];
      Rec.Top := APoint.Y + 20;
      Rec.Left := APoint.X;
      Rec.Right := Rec.Left + HW.Canvas.TextWidth(sHint) + 6;
      Rec.Bottom := Rec.Top + HW.Canvas.TextHeight(sHint) + 4;
      HW.ActivateHint(Rec, sHint);
      HW.Refresh;
      Sleep(1000);
      HW.ReleaseHandle;
    finally
      HW.Free;
    end;
  end;
end;

<< Back to main page