RichTextBox SelectionStart超过TextLength(Winform c#)

时间:2013-08-22 09:51:57

标签: c# winforms richtextbox

这个问题让我抓狂。我有一个RTB,当按下空格键时我捕获RTB中输入的最后一个单词,并用VS intellisense弹出窗口中的一些建议单词替换它。一切都工作正常,除非我用超链接/表粘贴文本时RTB.SelectionStart属性变得大于RTB.Text.Length。从RTB.SelectionStart属性中,我捕获向左输入的字符,直到找到空格,然后反向输入最后一个字。但如果我粘贴一些超链接文本并开始写一些单词,我就不能这样做;因为现在RTB.SelectionStart变得比RTB.Text.Length更大;我无法使用RTB.Text.Substring方法捕获字符(向左)

如何在这种情况下正确获取当前光标位置?

编辑:

private string GetLastWord()
    {string word = "";
        int pos = rtfText.SelectionStart;
      //  int length = rtfText.Text.Length;
       // if (pos > length) pos = length;

            if (pos >= 1)
            {
                string tmp = "";
                var f = new char();

                while (f != ' ' && f != '-' && f != 10 && pos > 0)
                {
                    pos--;
                    tmp = rtfText.Text.Substring(pos, 1);
                    f = tmp[0];
                    word += f;
                }

                char[] ca = word.ToCharArray();
                Array.Reverse(ca);
                word = new String(ca);
            }
            // MessageBox.Show(word + ":" + word.Length);
            return word;
   }

0 个答案:

没有答案