Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haunted by C# ownerdraw treeview

Having a hard time understanding an ownerdraw treeview, here is the full story:

A VS2013 WinForms app (running on Windows 8.1 with TrueType enabled if that matters...) with a treeview with: DrawMode = OwnerDrawText;

In form load, some nodes are added to the treeview:

   private void Form1_Load(object sender, EventArgs e)
    {
        // add some nodes
        for (int i = 0; i < 20; i++)
        {
           TreeNode treeNode = treeView1.Nodes.Add(new String('i', 60));
           treeNode.Tag = i;
        }
    }

Next, I am drawing every other node myself to show the problem:

    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        // use ownerdraw every other item
        if ((int)(e.Node.Tag) % 2 == 0)
        { 
            Font font = e.Node.NodeFont;
            if (font == null) font = e.Node.TreeView.Font;
            e.Graphics.DrawString(e.Node.Text, font, Brushes.Red, e.Bounds.X, e.Bounds.Y);
        }
        else
        {
            e.DrawDefault = true;
        }
    }

Looking at the results, notice how the owner drawn (red) items nodes have an inter-character spacing that is different from when the treeview draws its own nodes. And after a while, the spacing suddenly changes. Am I using the wrong font here? Am I missing something obvious?

Thanks for your time.

like image 528
user4363553 Avatar asked Dec 15 '14 19:12

user4363553


1 Answers

Using TextRenderer.DrawText instead of Graphics.DrawString should fix this. Ian Boyd posted a wonderful answer about the difference between the two and why the text can look off when doing custom drawing.

I contemplated quoting a portion of his answer here, but in reality if you doing custom drawing you really ought to read that whole answer because every portion of it is significant when it comes to drawing text - especially when drawing only a portion of the text on a control as opposed to doing all the drawing yourself.

like image 140
Anthony Avatar answered Nov 04 '22 22:11

Anthony