How can I get the insert position of a TextBox when there is a choice?

If there is no selection in the TextBox, then the insertion position is SelectionStart.

But if there is a Selection, then the insertion position can be in SelectionStart (selection from right to left):

enter image description here

Or it could be in SelectionStart + SelectionLength (selection from left to right):

enter image description here

How then to determine the insertion position of a TextBox when there is a choice?

+4
source share
2 answers

There may be a way to cheat, but there is no natural way to do this.

If, for example, at the moment in the application you know that the text in the TextBox selected (no difference left-right or right-left) you can do

 textBox1.SelectionLength = 0; //this will clear a selection UI 

After this line, calling

 int caretPosition = textBox1.SelectionStart; 

will receive the actual Caret position for you.

By the way, this is a trick, so it’s better to avoid such decisions (maybe someone will suggest something else), and it’s better to slightly change the order of the code.

Hope this helps.

+1
source

An excellent explanation of the carriage position here, it is best to call your own API so that you do not violate the selection and other functions of the text field (for example, cancel)

http://www.microbion.co.uk/developers/C%20position%20of%20caret.pdf

0
source

All Articles