1. 程式人生 > >delphi自動調整combobox下拉列表寬度(PostMessage CB_SETDROPPEDWIDTH)

delphi自動調整combobox下拉列表寬度(PostMessage CB_SETDROPPEDWIDTH)

pro comment pbo for count h+ dropdown not wid

在combobox所在的窗口的Formshow事件裏調用即可

[delphi] view plain copy
  1. procedure SetComboBoxListWidth( AComboBox: TComboBox );
  2. var
  3. i: Integer;
  4. nMaxLen, nMinWidth: integer;
  5. nFontWidth: Integer;
  6. nCboLeft: integer;
  7. ctlCustom: TControl;
  8. begin
  9. nCboLeft := AComboBox.Left;
  10. ctlCustom := AComboBox;
  11. with AComboBox do
  12. begin
  13. nFontWidth := Round( Abs(Font.Height / 2 ) );
  14. nMaxLen:= 0;
  15. for i:=0 to Items.Count-1 do
  16. begin
  17. if length(Items[i])* nFontWidth > nMaxLen then
  18. nMaxlen:= length(Items[i])* nFontWidth+5;
  19. end;
  20. if Items.Count > DropDownCount then
  21. nMaxLen := nMaxLen + 20;
  22. if nMaxLen > Width then
  23. begin
  24. if Items.Count>DropDownCount then
  25. begin
  26. SendMessage( Handle, CB_SETHORIZONTALEXTENT, nMaxLen+5, 0 );
  27. {解決分辨率小導致的ComboboxList的寬度超出屏幕}
  28. //while 部分是用來取出combobox控件相對與窗體的橫坐標
  29. while not (ctlCustom.Parent is TForm) do
  30. begin
  31. nCboLeft := nCboLeft + ctlCustom.Parent.Left;
  32. ctlCustom := ctlCustom.Parent;
  33. end;
  34. nMinWidth := Min(400, nMaxLen); // 使用不大於nMaxLen的數做比較
  35. if (nCboLeft + nMinWidth) > Screen.Width-25 then // 不超出屏幕,並保留窗口滾動條寬度,約25
  36. nMinWidth := Screen.Width-25-nCboLeft;
  37. nMinWidth := Max(nMinWidth, Width); // 不小於控件自身寬度
  38. PostMessage(Handle, CB_SETDROPPEDWIDTH, nMinWidth, 0);
  39. end
  40. else
  41. PostMessage(Handle, CB_SETDROPPEDWIDTH, nMaxLen , 0);
  42. ShowHint := True;
  43. end
  44. else
  45. begin
  46. SendMessage( Handle, CB_SETHORIZONTALEXTENT, 0, 0 );
  47. PostMessage(Handle, CB_SETDROPPEDWIDTH, Width , 0);
  48. end;
  49. end;
  50. end;

http://blog.csdn.net/youthon/article/details/8179348

delphi自動調整combobox下拉列表寬度(PostMessage CB_SETDROPPEDWIDTH)