Search code examples
c#winformstextpositionrichtextbox

How to find the position of a single word of text in a form C#


I'm not sure if this is possible or not. I'm interested in being able to find the (x,y) position of a word of text on a WinForm.

For example, in the picture below, I want to be able to pull the (x,y) coordinate of the upper-left hand corner of the letter H in "HERE".

I know how to get the position of textbox, so I can make a rough estimate based off of where the word "HERE" is inside the textbox, but I would like to be able to just ask the program where the word is if that is possible.

Also, if there is a way to get that position, I'd like to be able to get the length and height of the word (Basically I want to know the coordinates of the bounding box of the word "HERE" if possible)

Not sure if this matters, but the textbox is a richTextBox, and the textbox is populated from a string array in the Form1 class.

Thank you in advance!

enter image description here


Solution

  • You can use GetPositionFromCharIndex method, to get position of "HERE" within the TextBox or RichTextBox (it works for both).

    As you probably know, to get position in the window you have to sum this up with position of your richTextBox. Like this:

    int index = richTextBox1.Text.IndexOf("HERE");
    Point textBoxLocation = richTextBox1.GetPositionFromCharIndex(index);
    Point windowsLocation = new Point(richTextBox1.Location.X + textBoxLocation.X, richTextBox1.Location.Y + textBoxLocation.Y);
    Console.WriteLine("Position in textbox: " + textBoxLocation.ToString());
    Console.WriteLine("Position in window: " + windowsLocation.ToString());