简体   繁体   English

插入rtf字符串时RichTextBox插入符的位置

[英]RichTextBox caret position when inserting rtf string

I am trying to insert string into a RichTextBox . 我正在尝试将字符串插入RichTextBox This is the KeyUp event form RichTextBox : 这是KeyUp事件表单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 . 我注意到只有在修改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? 您甚至怎么知道在索引750上您有文本和控制字符?

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. 当然,如果您尝试将插入符号放置在插入void的位置,那么这对您的属性无效,因为和text属性是不同的东西。

If trying to insert text in the text property, then it would look something like this: 如果尝试在text属性中插入文本,则它将类似于以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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