delphi自动调整combobox下拉列表宽度

在combobox所在的窗口的Formshow事件里调用即可

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;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值