Called in the Formshow event of the window where the ComboBox is located
[Delphi]View PlainCopy
- Procedure Setcomboboxlistwidth (Acombobox:tcombobox);
- Var
- I:integer;
- Nmaxlen, nminwidth: integer;
- Nfontwidth:integer;
- Ncboleft: integer;
- Ctlcustom:tcontrol;
- Begin
- Ncboleft: = Acombobox. Left;
- Ctlcustom: = Acombobox;
- With acombobox do
- begin
- Nfontwidth: = Round (Abs (Font. Height/ 2));
- nmaxlen:= 0;
- For i:=0 to Items. count-1 do
- begin
- if Length (items[i]) * nfontwidth > Nmaxlen Then
- nmaxlen:= length (items[i]) * nfontwidth+5;
- end;
- if Items. Count > Dropdowncount Then
- Nmaxlen: = Nmaxlen + 20;
- if Nmaxlen > Width Then
- begin
- if Items. Count>dropdowncount Then
- begin
- SendMessage (Handle, Cb_sethorizontalextent, nmaxlen+5, 0);
- {Resolution Small causes the width of the comboboxlist to exceed the screen}
- The //while section is used to remove a ComboBox control relative to the horizontal axis of the form
- While not (Ctlcustom. Parent is tform) do
- begin
- Ncboleft: = Ncboleft + Ctlcustom. Parent. Left;
- Ctlcustom: = Ctlcustom. Parent;
- end;
- Nminwidth: = Min (n, Nmaxlen); //Use a number less than Nmaxlen to compare
- if (ncboleft + nminwidth) > Screen. width- then//do not exceed the screen and keep the window scroll bar width, approx.
- Nminwidth: = Screen. width-25-ncboleft;
- Nminwidth: = Max (Nminwidth, Width); //not less than the width of the control itself
- PostMessage (Handle, Cb_setdroppedwidth, Nminwidth, 0);
- End
- Else
- PostMessage (Handle, Cb_setdroppedwidth, Nmaxlen, 0);
- Showhint: = True;
- End
- Else
- begin
- SendMessage (Handle, Cb_sethorizontalextent, 0, 0);
- PostMessage (Handle, Cb_setdroppedwidth, Width, 0);
- end;
- end;
- End
http://blog.csdn.net/youthon/article/details/8179348
Delphi automatically adjusts the ComboBox drop-down list width (PostMessage cb_setdroppedwidth)