Tom
Tom

Reputation: 857

How can I get the insertion position of a TextBox when there is a selection?

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

But if there is a Selection, then the insertion position might be at SelectionStart (right-to-left selection):

enter image description here

Or it might be at SelectionStart + SelectionLength (left-to-right selection):

enter image description here

How, then, does one figure out the insertion position of a TextBox when there is a selection?

Upvotes: 4

Views: 564

Answers (2)

Justin King
Justin King

Reputation: 1428

Great explanation on caret position here, best to call native API that way you don't break selection and other textbox functions (such as undo)

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

Upvotes: 0

Tigran
Tigran

Reputation: 62256

There could be a way to trick, but there is no natural way of doing that.

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

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

After this line by calling

int caretPosition =  textBox1.SelectionStart;

will retrieve actually a Caret position to you.

By the way this is a trick, so it's better to avoid these kind of solutions (may be there will be someone offering something else) and it's better to slightly rearrange the code.

Hope this helps.

Upvotes: 1

Related Questions