0

I have a class inheriting from CheckedListBox in Windows Forms and it contains two items. The problem is the following: When I try to increase the ItemHeight, the height will be changed, but the text is in the top left corner of the bounding box.

Image

I want it to be vertically aligned in the center of that bounding box. I can't seem to find any property that would do so. I tried to use the DrawItem event like this

public MyCheckedList()
{
    this.DrawMode = DrawMode.OwnerDrawVariable;
    this.DrawItem += new 
    System.Windows.Forms.DrawItemEventHandler(this.OnDrawItem);
}

public override int ItemHeight
{
    get; set;
}

public override DrawMode DrawMode
{
    get; set;
}

public void OnDrawItem(object sender, DrawItemEventArgs e)
{
    CheckedListBox list = (CheckedListBox)sender;
    if (e.Index > -1)
    {
        object item = list.Items[e.Index];
        e.DrawBackground();
        e.DrawFocusRectangle();
        TextRenderer.DrawText(e.Graphics, item.ToString(), list.Font, e.Bounds, list.ForeColor);
    }
}

Well, the program doesn't even enter the OnDrawItem() method. It's also strange that I have to override ItemHeight and DrawMode to make them work properly. Is there maybe another way?

Vy Do
  • 46,709
  • 59
  • 215
  • 313
HimmDawg
  • 97
  • 10
  • 1
    You need to pass `TextFormatFlags` to `TextRenderer.DrawText()` which specify that the string should be rendered centered vertically. See whether you also need to specify to either clip or wrap the text. [Example with a ListBox](https://stackoverflow.com/a/60589434/7444103) – Jimi Mar 23 '21 at 14:15
  • This seems to do the trick, thanks :) As I stated, my code doesn't even reach the `OnDrawItem()` method. After a bit of research, I've found [this article](https://stackoverflow.com/questions/18725111/can-i-use-a-drawitem-event-handler-with-a-checkedlistbox) stating that it's not as easy as overwriting the `DrawItem` event. – HimmDawg Mar 24 '21 at 14:12

0 Answers0