简体   繁体   中英

RichTextBox caret position when inserting rtf string

I am trying to insert string into a RichTextBox . This is the KeyUp event form RichTextBox :

private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
    string st = richTextBox1.Rtf;
    st=st.Insert(750, "void");
    richTextBox1.Rtf = st;
}

The problem is that, after each update, the caret goes before the inserted text and I want to keep it at the end. I noticed that this is happening only when I modify the length of st .

I can't fathom how your code is supposed to work for the end user. How would you even know that at index 750 you have text versus an control character?

The quick solution is to just set the caret position to the end yourself:

private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
    string st = richTextBox1.Rtf;
    st=st.Insert(750, "void");
    richTextBox1.Rtf = st;
    richTextBox1.SelectionStart = richTextBox1.TextLength;
}

Of course, if you are trying to put the caret at the position where void is inserted, that wouldn't work with your property, since the and text properties are different things.

If trying to insert text in the text property, then it would look something like this:

private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
    string st = richTextBox1.Text;
    st=st.Insert(750, "void");
    richTextBox1.Text = st;
    richTextBox1.SelectionStart = 750 + 4;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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