Cuadro de texto SelectionStart, SelectionEnd y Caret (cursor) Posición

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.

preguntado el 01 de febrero de 12 a las 22:02

2 Respuestas

Necesita configurar el SelectionLength to 0 as anotado en la documentación.

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 aquí.

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

Entonces podrías llamar SetCaretPos.

contestado el 23 de mayo de 17 a las 14:05

Si configura el 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);

Respondido el 30 de enero de 19 a las 23:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.