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):
Or it might be at SelectionStart + SelectionLength (left-to-right selection):
How, 开发者_JAVA技巧then, does one figure out the insertion position of a TextBox when there is a selection?
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.
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
精彩评论