RichTextBox C# 设置光标位置 WinForms

3
我正在构建一个聊天应用程序,用户将其文本输入到rich textbox中。
在rich text box中有一段初始文本,其中写着:“我:”。
现在,当用户按下Home键时,我希望光标位于“我:”字符串之后。因此,对于Shift + Home组合键、三次鼠标单击或Ctrl +左箭头等任何方式,都可以实现这个目标。
有什么方法可以做到吗?
我已经尝试过
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetCaretPos(int X, int Y);

感谢您的提前帮助,Oz。
谢谢。
5个回答

8
您可以使用富文本框的 SelectionStartSelectionLength 属性来设置插入符位置。将 SelectionLength 设置为 0,然后将 SelectionStart 设置为所需插入符出现的位置。 SelectionStart 的文档说明如下:

如果在控件中没有选定文本,则此属性指示新文本的插入点或插入符。


Win32 API 函数 SetCaretPos 对您的需求过于低级。

4

由于宽限期的存在,现在看起来我仿佛抄袭了你的答案!;-) - undefined
确实哈哈,我编辑完后才看到你已经发布了。 - undefined

4
使用 Select 方法:
public void Select(
    int start,
    int length
)

richTextBoxUserText.Select(richTextBoxUserText.TextLength, 0);

0
RichTextBox1.SelectionStart = Pos;
RichTextBox1.SelectionLength = 0;
RichTextBox1.ScrollToCaret();

-2
在谷歌上搜索到了SelectionProtected属性。
richTextBoxUserText.Text = INITIAL_TEXT;
richTextBoxUserText.SelectAll();
richTextBoxUserText.SelectionColor = Color.Red;
richTextBoxUserText.SelectionProtected = true;
richTextBoxUserText.SelectionLength = 0;
richTextBoxUserText.SelectionStart = richTextBoxUserText.TextLength + 1;

@David,保护文本不被删除的解决方案是使用SelectionProtected属性。为了防止用户选择它,还需要进行额外的工作...你在哪里告诉我这个? - undefined
3
你的原始问题中没有提到保护文本。此外,我相当确定“richTextBoxUserText.SelectionStart = richTextBoxUserText.TextLength + 1”会引发一个越界异常。 - undefined
@David是的,我没有提到,因为我不知道...而且它不会抛出异常。 - undefined
2
@oz 对不起,我没有提到保护的问题,但是我没有看到你问题中的那部分。 - undefined
@oz 好吧,但我对此感到惊讶...你将选择设置为文本末尾 + 1。 - undefined
2
如果您将此属性设置为超出控件中文本长度的位置,选择起始位置将放置在最后一个字符之后。这就解释了...您那粗糙的编码得到了补偿! :) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接