0

I have in c# a treeView/treeNode and want to highlight parts of the nodes text. For this I already found a good solution: https://stackoverflow.com/a/13824463/2925238 but unfortunately the string parts seem to be wrongly measured and/or drawn.

To better show this I alternating highlighted every 5 chars: drawing glitch

Here the original with no OwnerDrawing: original

It seems that the Graphics.DrawString-method adds some space to the beginning and the Graphics.MeasureString-method computes a false length (the longer the string part, the longer the wrong adding).

Does anyone know, why and how to get rid of this?

Thanks in advance :-)


Here my code for DrawNode:

string txt = e.Node.Text;
int crt = 0;
float posX = e.Bounds.Left, posY = e.Bounds.Top;
string sub;
bool flag = false;
using (Font font = new System.Drawing.Font(tvSearchResults.Font, System.Drawing.FontStyle.Regular))
{
    while (crt < txt.Length)
    {
        using (Brush brush = new SolidBrush(flag ? Color.Black : Color.Blue))
        {
            sub = (crt + 5 < txt.Length) ? txt.Substring(crt, 5) : txt.Substring(crt);
            e.Graphics.DrawString(sub, font, brush, posX, posY);
            SizeF siz = e.Graphics.MeasureString(sub, font);
            posX += siz.Width;
            crt += 5;
            flag = !flag;
        }
    }
}
casiosmu
  • 797
  • 1
  • 8
  • 22
  • Ah, thank you very much – casiosmu Sep 29 '16 at 08:09
  • Hmm, there are still problems: to add a StringFormat to the Draw/MeasureString-methods get me rid of the spacing. The switch to the TextRenderer-methods had unfortunately absolute no effect - looks the same as the first image! It also seems that the bounds of the node are not updated... If I click at a node, the highlight rectangle is too short. Do I have to draw it manually, too? – casiosmu Sep 29 '16 at 09:32

0 Answers0