Question

I want to do some visual changes on listbox items so i set DrawMode to "OwnerDrawFixed" i want the text to be the middle of the item vertivally it was easy by doing this:

private void listTypes_DrawItem(object sender, DrawItemEventArgs e)
{
   e.DrawBackground();
   e.Graphics.DrawString(listTypes.Items[e.Index].ToString(),
                e.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top + e.Bounds.Height/4
                , StringFormat.GenericDefault);  
   e.DrawFocusRectangle();  
}

but to center the text horizentally i need to know the text width how to get it or is there a better way to do this

Was it helpful?

Solution

You can try with code

    void listTypes_DrawItem(object sender, DrawItemEventArgs e)
    {
        ListBox list = (ListBox)sender;
        if (e.Index > -1)
        {
            object item = list.Items[e.Index];
            e.DrawBackground();
            e.DrawFocusRectangle();
            Brush brush = new SolidBrush(e.ForeColor);
            SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font);
            e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); 
        }
    }

OTHER TIPS

You should use TextRenderer.DrawText() to make the text appearance consistent with the way text is rendered by the other controls in your form. Which make it easy, it already has an overload that accepts a Rectangle and centers the text inside that rectangle. Just pass e.Bounds. You also need to pay attention to the item state, using a different color for the selected item. Like this:

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
        e.DrawBackground();
        if (e.Index >= 0) {
            var box = (ListBox)sender;
            var fore = box.ForeColor;
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) fore = SystemColors.HighlightText;
            TextRenderer.DrawText(e.Graphics, box.Items[e.Index].ToString(),
                box.Font, e.Bounds, fore);
        }
        e.DrawFocusRectangle();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top