RichTextBox C# Set caret location winforms

这一生的挚爱 提交于 2019-12-02 02:49:46

问题


I am building a chat application where the user enters its text to a richtextbox.

In the rich text box there is an initial text which says: "Me: ".

Now, when the user press the Home button I want the caret to be located after the "Me: " string. So for Shift+Home combination or for triple mouse click or for Ctrl + left cursor etc..

Any way it can be done?

I've already tried

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

thanks in advance, Oz.


回答1:


You can set the caret position with the SelectionStart and SelectionLength properties of the rich text box. Set SelectionLength to 0 and then set SelectionStart to the location where you want the caret to appear.

The documentation for SelectionStart says:

If no text is selected in the control, this property indicates the insertion point, or caret, for new text.


The Win32 API function SetCaretPos is much too low level for your needs.




回答2:


Winforms: RichTextBox.SelectionStart & set RichTextBox.SelectionLength to 0.

WPF: RichTextBox.CaretPosition




回答3:


Use the Select method:

public void Select(
    int start,
    int length
)

richTextBoxUserText.Select(richTextBoxUserText.TextLength, 0);



回答4:


Found it googling on the property SelectionProtected

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


来源:https://stackoverflow.com/questions/6441455/richtextbox-c-sharp-set-caret-location-winforms

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