I have tried a lot of things.
Rectangle r = checkedListBox1.GetItemRectangle(0);
checkedListBox1.ClientSize = new Size(checkedListBox1.PreferredSize.Width, checkedListBox1.PreferredSize.Height);
Here I tried resizing the ClientSize
to the PreferredSizes
, this doesn't seem to always work. An odd note is that PreferredSize.Height
is not always correct if I don't previously call GetItemRectangle().
I have tried capturing the maximum bounds on OnDrawItem
with no luck because this only gives information about whats being painted.
I have tried iterating over each element using TextRenderer.MeasureText()
I have tried creating a fake graphics class along with graphics.MeasureString()
to measure it in a simular fashion to which it was painted.
foreach (string selection in this.Items)
{
Image tmpImg = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(tmpImg);
StringFormat format = new StringFormat(StringFormat.GenericTypographic);
format.Trimming = StringTrimming.None;
format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
SizeF size = graphics.MeasureString(selection, this.Font, 0, format);
float selectionWidth = size.Width + PaddingRecommendedByMSDN + CustomCheckBoxWidth;
if (selectionWidth > maxWidth)
maxWidth = (int)selectionWidth;
}
Rectangle r = this.GetItemRectangle(0);
this.ClientSize = new Size((int)maxWidth , this.PreferredSize.Height );
Although this last solution seems to be the most accurate. It still is slightly off on large strings.
Does anyone know where I can properly capture the maximum width of the item contents of a CheckedListBox? I'm just trying to make the width fill the CheckedListBox so there are no scrolls shown. PreferredSize.Height never seems to fail me, only the width.