Treenode text of different colored words

I have a TreeView , and each of them Node.Text has two words. The first and second words must have different colors. I already change the color of the text using the DrawMode and DrawNode , but I cannot figure out how to divide Node.Text into two different colors. Someone pointed out that I can use TextRenderer.MeasureText , but I have no ideals how and where to use it.

Does anyone have an idea?


The 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); } 
+1
source share
1 answer

Try the following:

  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 the State node to perform assignable actions.

UPDATE

Sorry, my error is an updated version. There is no need to measure the size of the space, as it is already contained in texts[0] .

+6
source

All Articles