When the length of a string in a combobox exceeds the width of the combobox there are 3 things that can be done they are
Shorten the string (not a very good solution)
Add a horizontal scroll bar
Change the width of the drop down list.
The following function will reset the width of the dropdown listbox within a combobox.
It takes 2 parameters (1 optional).
ComboBox is the TComboBox whos dropdown width is to be changed.
Width is an optional parameter specifying the width of the drop down list. If
the width is less than the width of the ComboBox then this parameter will be ignored and the width will be set to the longest string in the combobox.
procedure SetComboDropDownWidth(ComboBox: TComboBox; Width: Integer = -1);
var
I, TextLen: Longint;
lf: LOGFONT;
f: HFONT;
begin
if Width < ComboBox.Width then begin
FillChar(lf,SizeOf(lf),0);
StrPCopy(lf.lfFaceName, ComboBox.Font.Name);
lf.lfHeight := ComboBox.Font.Height;
lf.lfWeight := FW_NORMAL;
if fsBold in ComboBox.Font.Style then
lf.lfWeight := lf.lfWeight or FW_BOLD;
f := CreateFontIndirect(lf);
if (f <> 0) then
begin
try
ComboBox.Canvas.Handle := GetDC(ComboBox.Handle);
SelectObject(ComboBox.Canvas.Handle,f);
try
for I := 0 to ComboBox.Items.Count -1 do begin
TextLen := ComboBox.Canvas.TextWidth(ComboBox.Items[I]);
if TextLen > Width then
Width := TextLen;
end;
(* Standard ComboBox drawing is Rect.Left + 2,
adding the extra spacing offsets this *)
Inc(Width, GetSystemMetrics(SM_CYVTHUMB) +
GetSystemMetrics(SM_CXVSCROLL));
finally
ReleaseDC(ComboBox.Handle, ComboBox.Canvas.Handle);
end;
finally
DeleteObject(f);
end;
end;
end;
SendMessage(ComboBox.Handle, CB_SETDROPPEDWIDTH, Width, 0);
end;