6

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.

user4363553
  • 103
  • 1
  • 8
  • 1
    Its worthwhile to note that we *cant* see the results. You may want to provide a screenshot. Otherwise, nice first question! – BradleyDotNET Dec 15 '14 at 19:07
  • Wooops, my original question had the picture, but as I have never helped somebody else here (I know: *shame* *blush* I will better myself) I was not allowed to upload a picture with the question. I go and try to fix that soon. – user4363553 Dec 15 '14 at 21:03
  • If you post a link, a higher-rep user will often help you out. – BradleyDotNET Dec 15 '14 at 21:04

1 Answers1

8

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.

Community
  • 1
  • 1
Anthony
  • 9,451
  • 9
  • 45
  • 72
  • Yes this works! Changing the Draw string line to: TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, Color.Red); Shows everything as it should. I wanted to UP your answer as the answer, but I seem to lack the credibility points to do so. Anyways: thanks a lot for helping me out, this has been bugging me for too long! – user4363553 Dec 15 '14 at 21:03