2

I have a TreeView and each of it's Node.Text has two words. The first and second words should have different colors. I'm already changing the color of the text with the DrawMode properties and the DrawNode event but I can't figure out how to split the Node.Text in two different colors. Someone pointed out I could use TextRenderer.MeasureText but I have no idead how/where to use it.

Someone has an idea ?


Code :

formload()
{
  treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
}

private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) 
{
Color nodeColor = Color.Red;
if ((e.State & TreeNodeStates.Selected) != 0)
  nodeColor = SystemColors.HighlightText;

 TextRenderer.DrawText(e.Graphics,
                    e.Node.Text,
                    e.Node.NodeFont,
                    e.Bounds,
                    nodeColor,
                    Color.Empty,
                    TextFormatFlags.VerticalCenter);
}
phadaphunk
  • 12,785
  • 15
  • 73
  • 107

1 Answers1

8

Try this:

    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        string[] texts = e.Node.Text.Split();
        using (Font font = new Font(this.Font, FontStyle.Regular))
        {
            using (Brush brush = new SolidBrush(Color.Red))
            {
                e.Graphics.DrawString(texts[0], font, brush, e.Bounds.Left, e.Bounds.Top);
            }

            using (Brush brush = new SolidBrush(Color.Blue))
            {
                SizeF s = e.Graphics.MeasureString(texts[0], font);
                e.Graphics.DrawString(texts[1], font, brush, e.Bounds.Left + (int)s.Width, e.Bounds.Top);
            }
        }
    }

You must manage State of node to do appropriated actions.

UPDATE

Sorry, my mistake see updated version. There is no necessary to measure space size because it already contains in texts[0].

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
  • Genius !! There is a slight problem with the highlight that doesn't highlight the whole text. But i'll figure out how to correct this. Just one more thing. Is there a way I could catch a node with a single word in it ? (crashes the program on the last line) because it's a rare but possible outcome. – phadaphunk Dec 11 '12 at 16:43
  • If you tried it with your program maybe you encountered this glitch(will post in another question) I implemented something similar to the solution you gave me one week ago and had a graphic glitch where the node does not draw at the right place. That's why I asked today again but the glitch is still here. – phadaphunk Dec 11 '12 at 17:01
  • the question is here thanks !! http://stackoverflow.com/questions/13825167/multicolor-treeview-draw-glitch – phadaphunk Dec 11 '12 at 17:16