Textbox SelectionStart, SelectionEnd and Caret (Cursor) Position

江枫思渺然 提交于 2019-12-14 01:43:35

问题


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.


回答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.

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

You could then call SetCaretPos.




回答2:


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);


来源:https://stackoverflow.com/questions/9104320/textbox-selectionstart-selectionend-and-caret-cursor-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!