Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting keywords in a richtextbox in WPF [duplicate]

I'm making a program which needs to look through a paragraph of text and find how many times a certain keyword/keywords appear. It also has to highlight each of these key words in the text.

I have managed to make he interface and it can now track how many times the word appears but I am really stuck for how to highlight where the keywords appear. I will post my code below, any help is greatly appreciated on how to search for and highlight text inside a richtextbox. Since this is in WPF the obvious richtextbox.find() is not avaliable for use.

class TextAnalyser
{
    public int FindNumberOfOccurances(List<string> keywords, string email)
    {
        int occurances = 0;
        foreach (string keyword in keywords)
        {
            occurances += email.ToUpper().Split(new string[] { keyword.ToUpper() }, StringSplitOptions.None).Count() - 1; 
        }
        return occurances;
    }

    public void TurnTextRed(List<string> keywords, string email, RichTextBox TextBox)
    {
        foreach(string keyword in keywords)
        {
        }
    }

    public List<string> ConvertTextToList(string text)
    {
        char[] splitChars = {};
        string[] ArrayText = text.Split( splitChars, StringSplitOptions.RemoveEmptyEntries);
        return ArrayText.ToList<string>();
    }

    public string GetStringFromTextBox(RichTextBox TextBox)
    {
        var textRange = new TextRange(
            TextBox.Document.ContentStart,
            TextBox.Document.ContentEnd
        );
        return textRange.Text;
    }
}

And here is my Main Window

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void AnalyseButton_Click(object sender, RoutedEventArgs e)
    {
        var textTool = new TextAnalyser();
        var keyWords = textTool.ConvertTextToList(textTool.GetStringFromTextBox(WordTextBox).Trim());
        var email = textTool.GetStringFromTextBox(EmailTextBox).Trim();
        int usesOfWord = textTool.FindNumberOfOccurances(keyWords, email);
        Occurances.Text = usesOfWord.ToString();
    }
}
like image 906
Needham Avatar asked Dec 09 '22 04:12

Needham


1 Answers

Here is the method is used to get all of word in richtextbox's document.

 public static IEnumerable<TextRange> GetAllWordRanges(FlowDocument document)
     {
         string pattern = @"[^\W\d](\w|[-']{1,2}(?=\w))*";
         TextPointer pointer = document.ContentStart;
         while (pointer != null)
         {
             if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
             {
                 string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                 MatchCollection matches = Regex.Matches(textRun, pattern);
                 foreach (Match match in matches)
                 {
                     int startIndex = match.Index;
                     int length = match.Length;
                     TextPointer start = pointer.GetPositionAtOffset(startIndex);
                     TextPointer end = start.GetPositionAtOffset(length);
                     yield return new TextRange(start, end);
                 }
             }

             pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
         }
     }

You can change the pattern which is used to split words.

At last, easy to highlight your words.

  IEnumerable<TextRange> wordRanges = GetAllWordRanges(RichTextBox.Document);
        foreach (TextRange wordRange in wordRanges)
        {
            if (wordRange.Text == "keyword")
            {
                wordRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
            }
        }
like image 179
HungDL Avatar answered Dec 10 '22 19:12

HungDL