TAGS :Viewed: 25 - Published at: a few seconds ago

[ Textbox SelectionStart, SelectionEnd and Caret (Cursor) Position ]

This could be very simple.

I have a textbox on a WinForm, Text = "ABCDEFGH". I need to select "BCD" and leave the I-Beam (cursor, caret, blinking '|') right between the 'A' and the 'B'. Setting SelectionStart = 1 and SelectionLenght = 3 doesn't work and I can't figure it out.

Answer 1

You need to set the SelectionLength to 0 as noted in the documentation.

You can programmatically move the caret within the text box by setting the SelectionStart to the position within the text box where you want the caret to move to and set the SelectionLength property to a value of zero (0).

If the issue is that BCD is in fact selected, yet you want the cursor moved back before the B I don't believe you will be able to do that via the framework properties since selecting text will move the cursor to the end of the text. You would need to use coordinates and a native interop as noted here.

[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCaretPos(out Point lpPoint);

You could then call SetCaretPos.