WPF: Way to count characters in actual line richTextBox.

TheDoublen 41 Reputation points
2022-02-08T14:36:47.693+00:00

Hi Team,

I have a WPF application where I use RichTextBox (rtb1) and I would like to know how many characters are in one line.

  • First I need to get the actual line in rtb1 and set this somehow to start of a TexPointer (I think....).
  • Then, I would like to count the characters in one line( e.g. current line).

I tied some mode, but none of them not working.
For e.g.: one line is: "this is a example text" -->22 char.

the following way give us only the total characters in entire rtb1. But I need only one line.

            TextPointer tp0 = rtb1.Document.ContentStart;

            TextPointer tp1 = rtb1.Document.ContentEnd;

            TextRange TR = new TextRange(tp1, tp0);
            int indexTP = TR.Text.Length;           // it's give the total characters in rtb1.

...

Someone can advice a way me and give little help? :)

Thank you for your help.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 48,046 Reputation points
    2022-02-08T16:03:05.183+00:00

    Be aware that RTF supports more than text so line X may not be text line X. Ignoring that aspect there are a couple of approaches. The simplest approach is to get all the text in a text range and then split on the new line.

    int GetLineLength ( RichTextBox box, int lineNumber )
    {
       var range = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
       var lines = range.Split('\n');
    
       return (lines.Length >= lineNumber) ? lines[lineNumber - 1] : -1;
    }
    

    For large docs this may get slow so you could use more code and an optimization (not tested).

    int GetLineLength ( RichTextBox box, int lineNumber )
    {
       int currentLine = 0;
       foreach (var paragraph in box.Document.Blocks.OfType<Paragraph>())
       {
          foreach (var text in paragraph.Inlines.OfType<Run>())
          {
             ++currentLine;
             if (currentLine == lineNumber)
                return text.Text.Length;
          };
       };
    
       return -1;
    }
    

    Note that we're making the assumption here that each inline has 1 run per line which may or may not be true for your document. You should test it.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful