2004. augusztus 4., szerda

Display tooltips for dropped-down TComboBox items

Problem/Question/Abstract:

Is it possible to display tooltips for a combobox in dropped down state if the items are wider than the combo box? Or better: is there a way to (auto) adjust the size of the drop down listbox to ensure all items fit?

Answer:

function CalcMaxWidthOfStrings(Strings: TStrings; Font: TFont): Integer;
var
I: Integer;
Canvas: TCanvas;
begin
Assert(Assigned(Strings));
Assert(Assigned(Font));
Canvas := TCanvas.Create;
try
Canvas.Handle := GetDC(0);
try
Canvas.Font := Font;
Result := 0;
for I := 0 to Strings.Count - 1 do
Result := Max2Int(Result, Canvas.TextWidth(Strings[I]));
finally
ReleaseDC(0, Canvas.Handle);
Canvas.Handle := 0;
end;
finally
Canvas.free;
end;
end;

procedure AutoSizeComboDropDown(Combo: TComboBox; Offset: Integer = 0);
var
Max, Cx: Integer;
begin
Cx := GetSystemMetrics(SM_CXVSCROLL) * Ord(Combo.Items.count > Combo.DropDownCount);
{Adding 6 here rather than in the next statement assures there's enough space
for the left and right margin and borders, too. I also added an offset that
allows me to use the same function in custom draw combos for example to
display an icon in the left margin.}
Max := CalcMaxWidthOfStrings(Combo.Items, Combo.Font) + 6 + Offset;
if Max > (Combo.ClientWidth - Cx) then
Combo.Perform(CB_SETDROPPEDWIDTH, Max + Cx, 0)
else
Combo.Perform(CB_SETDROPPEDWIDTH, Combo.Width, 0);
end;

Nincsenek megjegyzések:

Megjegyzés küldése