Author: Peter Below
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:
1 2 function CalcMaxWidthOfStrings(Strings: TStrings; Font: TFont): Integer;
3 var4 I: Integer;
5 Canvas: TCanvas;
6 begin7 Assert(Assigned(Strings));
8 Assert(Assigned(Font));
9 Canvas := TCanvas.Create;
10 try11 Canvas.Handle := GetDC(0);
12 try13 Canvas.Font := Font;
14 Result := 0;
15 for I := 0 to Strings.Count - 1 do16 Result := Max2Int(Result, Canvas.TextWidth(Strings[I]));
17 finally18 ReleaseDC(0, Canvas.Handle);
19 Canvas.Handle := 0;
20 end;
21 finally22 Canvas.free;
23 end;
24 end;
25 26 procedure AutoSizeComboDropDown(Combo: TComboBox; Offset: Integer = 0);
27 var28 Max, Cx: Integer;
29 begin30 Cx := GetSystemMetrics(SM_CXVSCROLL) * Ord(Combo.Items.count >
31 Combo.DropDownCount);
32 {Adding 6 here rather than in the next statement assures there's enough space 33 for the left and right margin and borders, too. I also added an offset that 34 allows me to use the same function in custom draw combos for example to 35 display an icon in the left margin.}36 Max := CalcMaxWidthOfStrings(Combo.Items, Combo.Font) + 6 + Offset;
37 if Max > (Combo.ClientWidth - Cx) then38 Combo.Perform(CB_SETDROPPEDWIDTH, Max + Cx, 0)
39 else40 Combo.Perform(CB_SETDROPPEDWIDTH, Combo.Width, 0);
41 end;