简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM