简体   繁体   English

Textbox SelectionStart,SelectionEnd和Caret(光标)位置

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

This could be very simple. 这可能非常简单。

I have a textbox on a WinForm, Text = "ABCDEFGH". 我在WinForm上有一个文本框,Text =“ABCDEFGH”。 I need to select "BCD" and leave the I-Beam (cursor, caret, blinking '|') right between the 'A' and the 'B'. 我需要选择“BCD”并将I-Beam(光标,插入符号,闪烁'|')放在'A'和'B'之间。 Setting SelectionStart = 1 and SelectionLenght = 3 doesn't work and I can't figure it out. 设置SelectionStart = 1和SelectionLenght = 3不起作用,我无法弄明白。

If you set the TextBox.Multiline property to True, you can then do this by using a negative selection length. 如果将TextBox.Multiline属性设置为True,则可以使用负选择长度来执行此操作。 You need to use the Select() overload as SelectionLength will not permit negative values. 您需要使用Select()重载,因为SelectionLength不允许负值。

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

You need to set the SelectionLength to 0 as noted in the documentation . 您需要将SelectionLength设置为0,如文档中所述

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). 您可以通过将SelectionStart设置为文本框中您希望插入符号移动到的位置并将SelectionLength属性设置为零(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. 如果问题是BCD实际上是选中的,但是你希望光标在B之前移回我不相信你能通过框架属性这样做,因为选择文本会将光标移动到文本的末尾。 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 . 然后,您可以调用SetCaretPos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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