delphi自動調整combobox下拉列表寬度(PostMessage CB_SETDROPPEDWIDTH)
阿新 • • 發佈:2017-07-24
pro comment pbo for count h+ dropdown not wid
在combobox所在的窗口的Formshow事件裏調用即可
[delphi] view plain copy
- 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 );
- {解決分辨率小導致的ComboboxList的寬度超出屏幕}
- //while 部分是用來取出combobox控件相對與窗體的橫坐標
- while not (ctlCustom.Parent is TForm) do
- begin
- nCboLeft := nCboLeft + ctlCustom.Parent.Left;
- ctlCustom := ctlCustom.Parent;
- end;
- nMinWidth := Min(400, nMaxLen); // 使用不大於nMaxLen的數做比較
- if (nCboLeft + nMinWidth) > Screen.Width-25 then // 不超出屏幕,並保留窗口滾動條寬度,約25
- nMinWidth := Screen.Width-25-nCboLeft;
- nMinWidth := Max(nMinWidth, Width); // 不小於控件自身寬度
- 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自動調整combobox下拉列表寬度(PostMessage CB_SETDROPPEDWIDTH)