Roman Starkov
Roman Starkov

Reputation: 61382

How to select text in a TextBox with the caret positioned at the START of the selection?

I'm using a System.Windows.Forms.TextBox. It is possible to select text by using the keyboard in such a way that the caret is positioned at the start of the selection - by holding Shift and moving the caret to the left.

I would like to do the same programmatically.

For example, suppose I have a text box with the text "Some sample text". I would like the "sample" word to be selected, and the caret to be positioned just before the "s" in "sample".

If I do this:

textbox.SelectionStart = 5;
textbox.SelectionLength = 6;

then I get the word selected, but the caret is just after "e" in "sample".

If I do this:

textbox.SelectionStart = 11;
textbox.SelectionLength = -6;

I get an exception.

How can I position the caret at the start of the selection?

Upvotes: 0

Views: 559

Answers (2)

JimG
JimG

Reputation: 1782

Very few things are impossible...

textbox.select(11, 0);
SendKeys.Send("+{LEFT}+{LEFT}+{LEFT}+{LEFT}+{LEFT}+{LEFT}");

Upvotes: 1

RaYell
RaYell

Reputation: 70414

I don't that is possible to program. As it is stated in MSDN native windows controls displays a flashing caret at the end position regardless of the relative values of start and end.

Upvotes: 2

Related Questions