简体   繁体   中英

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.

If you set the TextBox.Multiline property to True, you can then do this by using a negative selection length. You need to use the Select() overload as SelectionLength will not permit negative values.

textBox.Select(1 + 3, -3);

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 .

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

You could then call SetCaretPos .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM