RichTextBox C#设置插入位置winforms

我正在构建一个聊天应用程序,用户将其文本输入到richtextbox。

在富文本框中有一个初始文本,上面写着:“我:”。

现在,当用户按下Home按钮时,我希望插入符号位于“Me:”字符串之后。 因此对于Shift + Home组合或三键鼠标或Ctrl +左光标等。

有什么方法可以做到吗?

我已经试过了

[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetCaretPos(int X, int Y); 

谢谢你,奥兹。

您可以使用富文本框的SelectionStartSelectionLength属性设置插入位置。 将SelectionLength设置为0,然后将SelectionStart设置为您希望插入符号出现的位置。

SelectionStart的文档说:

如果控件中未选择任何文本,则此属性指示新文本的插入点或插入符号。


Win32 API函数SetCaretPos级别太低,无法满足您的需求。

Winforms: RichTextBox.SelectionStart并将RichTextBox.SelectionLength设置为0。

WPF: RichTextBox.CaretPosition

使用Select方法:

 public void Select( int start, int length ) richTextBoxUserText.Select(richTextBoxUserText.TextLength, 0); 

发现它在属性SelectionProtected上谷歌搜索

 richTextBoxUserText.Text = INITIAL_TEXT; richTextBoxUserText.SelectAll(); richTextBoxUserText.SelectionColor = Color.Red; richTextBoxUserText.SelectionProtected = true; richTextBoxUserText.SelectionLength = 0; richTextBoxUserText.SelectionStart = richTextBoxUserText.TextLength + 1;