WPF RichTextBox - get whole word at current caret position

被刻印的时光 ゝ 提交于 2019-12-06 11:36:13

问题


I enabled spelling on my WPF richtextbox and I want to get the misspelled word at current caret position before the context menu with spelling suggestions is displayed.


回答1:


The new way

    void richTextBox1_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Back)
        {
            TextPointer start = richTextBox1.CaretPosition;
            string text1 = start.GetTextInRun(LogicalDirection.Backward);
            TextPointer end = start.GetNextContextPosition(LogicalDirection.Backward);
            string text2 = end.GetTextInRun(LogicalDirection.Backward);

            richTextBox1.Selection.Select(start, end);
            richTextBox1.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
            richTextBox1.Selection.Select(start, start);
            //e.Handled = true;
        }
    }



回答2:


Check this out http://www.dotnetfunda.com/articles/article842-spellchecker-in-wpf-.aspx

Right around here seems to discuss some options which may help your scenario: "Here we are using SpellingError class to get the Suggessions. CaretIndex returns the index where the carat is in the textbox. GetSpellingError can return SpellingError object only when the current Carat location has a word with errors and also SpellCheck is enabled for the TextBox. "




回答3:


The old way

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Back)
        {
            var z = this.richTextBox1.SelectionStart;
            var r = richTextBox1.Find(" ", 0, z, RichTextBoxFinds.None | RichTextBoxFinds.Reverse);
            var q = this.richTextBox1.Text.Substring(r + 1, z - r - 1);
            switch (q)
            {
                case "test":
                    this.richTextBox1.SelectionStart = r + 1;
                    this.richTextBox1.SelectionLength = z - r - 1;
                    this.richTextBox1.SelectionColor = Color.Black;
                    this.richTextBox1.SelectionStart += this.richTextBox1.SelectionLength;
                    this.richTextBox1.SelectionLength = 0;
                    //e.Handled = true;
                    break;
                default:
                    this.richTextBox1.SelectionStart = z;
                    break;
            }
        }
    }



回答4:


For future reference:

void richTextBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
   var rtb = (RichTextBox)sender;
   var tr = rtb.GetSpellingErrorRange(rtb.CaretPosition);
   if(tr != null)
   {
       string spellingerror = tr.Text;
       //Do whatever
   }
}


来源:https://stackoverflow.com/questions/3934422/wpf-richtextbox-get-whole-word-at-current-caret-position

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