How to get the CaretPosition on textbox using GetCaretPos() or any other method?

1.7k Views Asked by At

I am trying to make a new application on C#, as a part of this I want to know the caret position (The exact point within the control) on a rich text control box.

I will explain it: assume I have a win form, rich textcontrol box and a contextmenustrip. When I type a specific charector or string on textbox I want to pop up this contextmenu item.

For this reason I want to know the exact point of caret on that text box.

As a result of googling + SO articles I found a way through GetCaretPos(), but I am unable to use it.

I did something with richtextbox get functions. One is the following:

Point k= richTextBox1.GetPositionFromCharIndex((richTextBox1.Lines[richTextBox1.GetLineFromCharIndex(richTextBox1.GetFirstCharIndexOfCurrentLine())].Count() + 1));

I don't know if this is the exact point or not, but sometimes I am getting the correct value.

How can I fix the problem?

1

There are 1 best solutions below

0
On BEST ANSWER

Here's a quick way of seeing where the context menu would appear. Just make sure you subscribe to the event.

  private void richTextBox1_SelectionChanged(object sender, EventArgs e)
  {
     Point point = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
     Text = point.ToString ();// Write to window title for fun
     new ContextMenu(new MenuItem[] {new MenuItem("test")}).Show (richTextBox1, point);
  }