Click here to Skip to main content
15,073,511 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey guys,

I can't figure out if it is possible to programmatically select text in TextBox with also setting caret position? It always sets caret position to the end of selection:

http://i.imgur.com/VS8rKsK.png[^]

Can I get caret at the beginning of selection? (any other place?)

http://i.imgur.com/jiPz4dg.png[^]

Thanks!
Posted
Comments
BillWoodruff 11-Jan-16 4:20am
   
Why would you want to do this ? The standard relationship between cursor position and selection is something people expect to see.
chainerlt 11-Jan-16 4:30am
   
Believe me I wouldn't ask if I won't need that. Maybe I could do something with winapi or smth?
BillWoodruff 11-Jan-16 8:59am
   
I believe you :), but I still don't know why you need to do this, and, imho, knowing why could help you get an answer.

Unfortunately, in WinForms the Caret position is defined by the SelectionStart and SelectionLength properties, and you can't move it otherwise. So you can either select text, or set the caret to a specific position, but you can't do both.
You can in WPF - there is the CaretIndex property - but it isn't available in WinForms.
It can be done but you'd have to write your own textbox control, which is a lot of work!
   
What you say is not true. No, nothing sets a caret to the end of selection, and nothing sets a caret to the beginning of it. Your observation is incorrect. To make it clear, it's enough to select some text. You will see that the caret visually disappears; it is "replaced" by the selection. Play a bit with selecting text and you will see.

If you want, you can consider that the whole selected area becomes one big caret. Or, if you want, you can consider the caret as rendering of zero-length selection. This is precisely matched by the .NET API for TextBox selection: SelectionStart and SelectionLength. This way, conceptually, some text is "always selected".

—SA
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900