Mirror

How to detect which item of an open TComboBox dropdown list the mouse is over (Views: 713)


Problem/Question/Abstract:

How would I display a hint over items in a ComboBox dropdown if the item text of the highlighted item is wider than the dropdown? I also want to be able to do the same thing in a ListBox. For a ComboBox I don't know how to proceed. There is no ItemAtPos method for a ComboBox. My first thought was no problem, I'll look at the source for TListBox.ItemAtPos and create a TComboBox.ItemAtPos method. However, I ran into a wall. TListBox.ItemAtPos uses the LB_GetItemRect message to do its magic. There is no corresponding CB_GetItemRect message for a ComboBox. Does anyone out there have any ideas on how to proceed?

Answer:

procedure TForm1.appIdle(sender: TObject; var done: Boolean);
var
  pt: TPoint;
  wnd: HWND;
  buf: array[0..128] of Char;
  i: Integer;
begin
  GetCursorPos(pt);
  wnd := WindowFromPoint(pt);
  buf[0] := #0;
  if wnd <> 0 then
  begin
    GetClassName(wnd, buf, sizeof(buf));
    if StrIComp(buf, 'ComboLBox') = 0 then
    begin
      Windows.ScreenToClient(wnd, pt);
      i := SendMessage(wnd, LB_ITEMFROMPOINT, 0, lparam(PointToSmallpoint(pt)));
      if i >= 0 then
      begin
        SendMessage(wnd, LB_GETTEXT, i, integer(@buf));
        statusbar1.simpletext := buf;
        Exit;
      end;
    end;
  end;
  statusbar1.simpletext := '';
end;

As to showing a custom hint, there is a CM_HINTSHOW message that is send to a control before a hint is popped up. It comes with a pointer to a record that allows you to customize the hints position and the hint text. The thing is undocumented, like all the internal VCL messages, so you need to use the VCL source to figure out how it is used. Or search for examples in the newsgroups archives. When the mouse moves to the next item you call Application.Cancelhint to remove the old hint and wait for the new one to reappear. Application has a number of hint-related properties you can tweak to make the hint appear fast.

<< Back to main page