Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving CharOffset from TextPointer

Tags:

c#

I have this sequence in a RichTextBox: ABACADEF

I would like the user to hover over the sequence and for me to be able to know that they are looking at the Nth character in the sequence. If the user hovers over C I should get 4.

I have started with this code:

Point mousePosition = Mouse.GetPosition(richTextBox);
TextPointer position = richTextBox.GetPositionFromPoint(mousePosition, true);
int offset = richTextBox.Document.ContentStart.GetOffsetToPosition(position);

However, I cannot use GetOffsetToPosition(position); on the richTextBox as the text contains formatting so offsets don't match the values I expect. For instance instead of C returning 4 it might return 8 due to the formatting on the B. I would like to get the offset that ignores formatting.

I can see from debugging that TextPointer contains the member variable "CharOffset" which matches the value I want returned by position. However, I can't get access to it as far as I can see. Is there a method to access this value somewhere that I have missed or do I have to do this another way?

like image 319
Detritus Avatar asked Sep 16 '25 21:09

Detritus


1 Answers

I came here looking for an answer where I didn't need to use Reflection. However, seeing no answer, here's the answer using Reflection.

public static class TextPointerExtensions
{
    private static readonly PropertyInfo CharOffestProperty = typeof(TextPointer).GetProperty("CharOffset", BindingFlags.NonPublic | BindingFlags.Instance);
    public static int GetCharOffsetUsingReflection(this TextPointer textPointer)
    {
        return (int)CharOffestProperty.GetValue(textPointer);
    }
}
like image 196
Michael Wagner Avatar answered Sep 18 '25 10:09

Michael Wagner