Mega Code Archive

 
Categories / Delphi / VCL
 

Change the dropdown width of a TComboBox to the max length of the items

Title: Change the dropdown width of a TComboBox to the max length of the items Question: How can I change the listwidth of a ComboBox to the length of the larges item in the list? Answer: I changed the code of the article of Simon Carter's 'Setting the dropdown width of a combobox' so, so that you can use it with all the ComboBoxes in you app. Just put this procedure in your app (you need to declarate it ofcourse, and change TForm1 to the name of your Form): ----------------------------------------- procedure TForm1.DropDownWidth(Sender: TObject); var CBox: TDBComboBox; Width: Integer; I, TextLen: Longint; lf: LOGFONT; f: HFONT; begin CBox := (Sender as TDBComboBox); Width := CBox.Width; FillChar(lf,SizeOf(lf),0); StrPCopy(lf.lfFaceName, CBox.Font.Name); lf.lfHeight := CBox.Font.Height; lf.lfWeight := FW_NORMAL; if fsBold in CBox.Font.Style then lf.lfWeight := lf.lfWeight or FW_BOLD; f := CreateFontIndirect(lf); if (f 0) then try CBox.Canvas.Handle := GetDC(CBox.Handle); SelectObject(CBox.Canvas.Handle,f); try for i := 0 to CBox.Items.Count-1 do begin TextLen := CBox.Canvas.TextWidth(CBox.Items[i]); if CBox.Items.Count-1 CBox.DropDownCount then begin if TextLen Width-25 then Width := TextLen +25; end else if CBox.Items.Count-1 begin if TextLen Width-5 then Width := TextLen+8; end; end; finally ReleaseDC(CBox.Handle, CBox.Canvas.Handle); end; finally DeleteObject(f); end; SendMessage(CBox.Handle, CB_SETDROPPEDWIDTH, Width, 0); end; ----------------------------------------- Then, just call the procedure 'DropDownWidth' in the OnDropDown property of the ComboBox. And you're done. I hope I did this right, because this is my first Article and this is just the thirth procedure I made/changed to a procedure so so that it works for more than 1 object. YES! :D I hope it's usefull. Greets, Patrick van Dissel (BTW. I don't know if I may use HTML codes or not in an article... maybe something the webmaster(s) can put on the 'submit article' page, ThankS. And sorry for my english, I'm just 17 and english is not my first language :( )